【字符串】443. 压缩字符串

题目:

 

解答:

 1 class Solution {
 2 public:
 3     int compress(vector<char>& chars) 
 4     {
 5 
 6         if (chars.empty()) 
 7         {
 8             return 0;
 9         }
10             
11         size_t j = 0;
12         int cnt = 0;
13         for (size_t i = 1; i <= chars.size(); i++)
14         {
15             cnt++;
16             if (i == chars.size() || chars[i] != chars[j])
17             {
18                 j++;
19                 if (cnt != 1)
20                 {
21                     string scnt = to_string(cnt);
22                     for (auto c : scnt)
23                     {
24                         chars[j++] = c;
25                     }
26                 }
27 
28                 if (i == chars.size()) 
29                 {
30                     break;
31                 }
32                 
33                 chars[j] = chars[i];
34                 cnt = 0;
35             }
36         }
37 
38         return j;
39 
40     }
41 };

猜你喜欢

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