【Leetcode】面试题 01.06. 字符串压缩(每日一题)

题目链接: 字符串压缩


题意:字符串压缩。利用字符重复出现的次数,编写一种方法,实现基本的字符串压缩功能。比如,字符串aabcccccaaa会变为a2b1c5a3。若“压缩”后的字符串没有变短,则返回原先的字符串。你可以假设字符串中只包含大小写英文字母(a至z)。


题解:十分暴力的做法。跑了16ms。。我们开一个新字符串作为结果。

大概就是找到这个原来字符串的字符重复的地方做一个统计,统计出来的结果转字符串丢进结果集里。。


代码:

 1 class Solution {
 2 public:
 3     string compressString(string S) {
 4         string ss;
 5         int len = S.length();
 6         for(int i = 0,j = i+1;S[i]!='';){
 7             int cnt = 1;
 8             while(S[i] == S[j]){
 9                 j++;
10                 cnt++;
11             }
12             ss += S[i];
13             ss += to_string(cnt);
14             i = j;
15             j++;
16         }
17         int len1 = ss.length();
18         if(len1 >= len)  return S;
19         else    return ss;
20     }
21 };
原文地址:https://www.cnblogs.com/Asumi/p/12507086.html