【leetcode】443. String Compression
problem
Input ["a","a","b","b","c","c","c"] Output ["a","a","b","b","c","c"] Expected ["a","2","b","2","c","3"]
a:
Given an array of characters, compress it in-place. After you are done modifying the input array in-place, return the new length of the array.
ss
Input ["a","a","a","b","b","a","a"] Output ["a","5","b","2"] Expected ["a","3","b","2","a","2"]
ss
solution1:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Solution { public: int compress(vector<char>& chars) { if(chars.empty()) return 0; string res=""; char cur, pre; int num = 0; for(int i=0; i<chars.size(); i++) { cur = chars[i]; if(i==0) { res += cur; pre = cur; } if(cur!=pre) { if(num>1) res += to_string(num);// res += cur; pre = cur; num = 1; } else num++; } if(num>1) res += to_string(num); // int len = 0; if(res.size()> chars.size()) len = chars.size(); else if(res.size()<=chars.size()) { len = res.size(); for(int i=0;i<res.size(); i++) { chars[i] = res[i]; } } return len; } };
参考
1. Leetcode_443. String Compression;
完
各美其美,美美与共,不和他人作比较,不对他人有期待,不批判他人,不钻牛角尖。
心正意诚,做自己该做的事情,做自己喜欢做的事情,安静做一枚有思想的技术媛。
版权声明,转载请注明出处:https://www.cnblogs.com/happyamyhope/
心正意诚,做自己该做的事情,做自己喜欢做的事情,安静做一枚有思想的技术媛。
版权声明,转载请注明出处:https://www.cnblogs.com/happyamyhope/