使用两个数组分别记录字符和对应的数字,然后清除原来的vector,重新向里面添加元素。注意判断1个字符时,不将'1'加入vector。

int compress(vector<char>& chars) {
const int N = ;
char words[N];//存储字符
int count[N];//存储数字 memset(words, ' ', sizeof(words));//count初始化为全' '
memset(count, , sizeof(count));//count初始化为全0 char lastChar = ' ';//ASCII:32
int i = ;
for (auto c : chars)
{
if (c != lastChar)//新字符
{
if (lastChar == ' ')
{
i = ;
}
else
{
i++;
}
}
words[i] = c;
count[i]++;
lastChar = c;
} chars.clear();
for (int j = ; j <= i; j++)
{
chars.push_back(words[j]);
int a = count[j]; if (a == )
{
continue;
} char str[];
sprintf(str, "%d", a);
for (auto s : str)
{
if (s == '\0')
{
break;
}
chars.push_back(s);
}
}
int sum = chars.size();
return sum;
}

leetcode443的更多相关文章

  1. [Swift]LeetCode443. 压缩字符串 | String Compression

    Given an array of characters, compress it in-place. The length after compression must always be smal ...

  2. Leetcode443.String Compression压缩字符串

    给定一组字符,使用原地算法将其压缩. 压缩后的长度必须始终小于或等于原数组长度. 数组的每个元素应该是长度为1 的字符(不是 int 整数类型). 在完成原地修改输入数组后,返回数组的新长度. 进阶: ...

  3. 第六周 Leetcode 446. Arithmetic Slices II - Subsequence (HARD)

    Leetcode443 题意:给一个长度1000内的整数数列,求有多少个等差的子数列. 如 [2,4,6,8,10]有7个等差子数列. 想了一个O(n^2logn)的DP算法 DP[i][j]为 对于 ...

随机推荐

  1. python的常见排序

    在python程序中,我们往往自始至终都在与序列(列表.字典.元组)打交道,而最常用的操作就是对序列排序了.在此简单总结一下python中的排序. 基本排序方法 在python中,list对象具有 s ...

  2. 设计高效sql一般经验谈

      1不用在sql语句使用系统默认的保留关键字 2尽量用exists 和 not exists 代替 in 和 not in 这条在sql2005之后,在索引一样,统计信息一样的情况下,exists ...

  3. 工程优化方法中的“最速下降法”和“DFP拟牛顿法”的 C 语言实现

    这个小程序是研一上学期的“工程优化”课程的大作业.其实这题本可以用 MATLAB 实现,但是我为了锻炼自己薄弱的编码能力,改为用 C 语言实现.这样,就得自己实现矩阵的运算(加减乘除.求逆.拷贝):难 ...

  4. python中的变量与对象

    一. 什么是变量 变量就是以前学习的数学中常见的等式x = 3(x是变量,3是变量值),在编程中,变量不仅可以是数学,还可以是任意数据类型 二. 变量的命名规则 变量名必须是英文大小写.数字和_的组合 ...

  5. IaaS中的统一存储:从设计到实现

    转自:https://www.ustack.com/blog/tycc/ “原生的OpenStack并不支持统一存储,云主机服务Nova.镜像服务Glance.云硬盘服务Cinder的后端存储各不相同 ...

  6. nyoj-158-省赛来了(组合数)

    题目链接 /* Name:nyoj-158-省赛来了 Copyright: Author: Date: 2018/4/25 17:07:22 Description: 暴力,秒天秒地 */ #incl ...

  7. mysql-jdbc创建connection理解

    jdbc源码分析(http://blog.csdn.net/brilliancezhou/article/details/5499738) 创建JDBC连接代码 Class.forName(" ...

  8. LeetCode Student Attendance Record I

    原题链接在这里:https://leetcode.com/problems/student-attendance-record-i/description/ 题目: You are given a s ...

  9. 转: 全局变量报错:UnboundLocalError: local variable 'l' referenced before assignment

    http://blog.csdn.net/my2010sam/article/details/17735159

  10. swing之checkbox

    import java.awt.GridLayout; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax ...