【字符串】面试题 01.06. 字符串压缩

题目:

 

解答:

 1 class Solution {
 2 public:
 3     string compressString(string S) 
 4     {
 5         if (S.size() == 0) 
 6         {
 7             return S; // 空串处理
 8         }
 9 
10         string ans = "";
11         int cnt = 1;
12         char ch = S[0];
13         for (int i = 1; i < S.size(); ++i)
14         {
15             if (ch == S[i]) 
16             {
17                 cnt++;
18             }
19             else
20             {
21                 ans += ch + to_string(cnt); // 注意 cnt 要转为字符串
22                 ch = S[i];
23                 cnt = 1;
24             }
25         }
26         ans += ch + to_string(cnt);
27         return ans.length() >= S.size() ? S : ans;
28     }
29 };

猜你喜欢

转载自www.cnblogs.com/ocpc/p/12825439.html