[leetcode]443. String Compression
程序员文章站
2024-03-13 22:17:40
...
Given an array of characters, compress it in-place. The length after compression must always be smaller than or equal to the original array. Every element of the array should be a character (not int) of length 1. After you are done modifying the input array in-place, return the new length of the array.
Example 1:
Input: ["a","a","b","b","c","c","c"] Output: Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"]
分析:
原地压缩字符串,要求为每个字符只保留一个,后面为该字符原来出现的次数,最终返回新数组的长度。用变量cur来定位新数组中元素的位置,i来定位原数组中每个字符第一次出现的位置,j来记录每个字符出现的个数,转化为字符加入数组cur的后一位。
class Solution {
public:
int compress(vector<char>& chars) {
int len = chars.size();
int cur = 0;
for(int i = 0 , j = 0; i < len; i = j)
{
while(j < len && chars[i] == chars[j])
j++;
chars[cur++] = chars[i];
if(j - i == 1)
continue;
for(char c : to_string(j - i))
chars[cur++] = c;
}
return cur;
}
};
上一篇: 用PHP的socket实现客户端到服务端的通信实例详解
下一篇: PHP正则替换函数preg_replace()报错:Notice Use of undefined constant的解决方法分析
推荐阅读
-
leetcode 443. String Compression
-
[leetcode]443. String Compression
-
[leetcode]443. String Compression
-
443. String Compression
-
leetcode 1349 Maximum Students Taking Exam (dp state compression)
-
1.6 String Compression
-
UVA 1351 - String Compression
-
leetcode (String Compression)
-
LeetCode-String Compression
-
[String][3]Leetcode125. Valid Palindrome