443. String Compression
来源:互联网 发布:淘宝抢购秒杀要刷新吗 编辑:程序博客网 时间:2024/06/01 08:22
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.
Follow up:
Could you solve it using only O(1) extra space?
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"]Explanation:"aa" is replaced by "a2". "bb" is replaced by "b2". "ccc" is replaced by "c3".
该题要compress in-place
意味着不能做出新数组,那么要多的步骤是,压缩过程会不会有可能覆盖还没压缩的字母,最后要把多的部分删除。
第一个是字母,第二个跟数字,可知数字长度不会长于字母个数长度,因此第一个问题不会覆盖。
那么细节比较多,如要设置一个当前压缩后的位置,遍历数组的同时,不断压缩进去,压缩后的位置pre也要移动。还要增加判断条件字母个数为一个和多于一个的时候。
压缩的判断条件是,遍历数组的时候直到遇到非当前的字母。
class Solution {public: int compress(vector<char>& chars) { int temp = chars[0]; int pre=0; int size = chars.size(); int k = 1; for(int i=1;i<size;i++){ if(chars[i]==temp) k++; if(chars[i]!=temp){ chars[pre] = temp; if(k>1){ string s = to_string(k); for(int j=0;j<s.size();j++, pre++) chars[pre+1]=s[j]; pre++; }else{ pre++; } k=1; temp=chars[i]; } } chars[pre] = temp; if(k>1){ string s = to_string(k); for(int j=0;j<s.size();j++, pre++) chars[pre+1]=s[j]; } for(int i=pre+1;i<size;i++){ chars.pop_back(); } return chars.size(); }};
阅读全文
0 0
- 443. String Compression
- leetcode 443. String Compression
- 443. String Compression
- LWC 56:443. String Compression
- [Leetcode] 443. String Compression 解题报告
- Simple String Compression Functions
- String Compression LA4256
- UVALive 3363 String Compression
- LA 3363 String Compression
- UVA 1351 - String Compression
- Q1.5 String Compression
- 1.6 String Compression
- UVAlive-3363 String Compression
- CC150 1.6 String Compression
- weekly contest 56 第二题 443. String Compression
- UVA1351 UVALive 3363 String Compression
- LA 3363 String Compression(dp)
- uva1351 - String Compression 区间DP
- [JSOI2008]Blue Mary开公司
- Exe程序启动或结束进程 .bat
- C#学习之旅之数组与集合
- Win7操作系统:请求的操作需要提升
- 3.3.1 查询——JPQL/HQL
- 443. String Compression
- 【Scikit-Learn 中文文档】神经网络模型(无监督)- 无监督学习
- SQL入门 4 规格化过程
- Java基础知识学习之路-01
- Unable to instantiate application com.android.tools.fd.runtime.BootstrapApplication
- hdu 2818
- 统计和生成不同的二叉树
- C# string类应用
- 6.jquery插件