面试题 01.06. 字符串压缩
生活随笔
收集整理的這篇文章主要介紹了
面试题 01.06. 字符串压缩
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
2020-03-16
1.題目描述
字符串壓縮2.解題思路
用一個字符變量c存放第一個不同的字符,然后遍歷其后面的字符,如果相同則cnt加一,否則更新c 以及cnt,注意這里的cnt是可能大于10的。 string添加字符:+=c; string添加數字:+=to_string(cnt);3.代碼
#include <iostream> #include <cstring> using namespace std;class Solution { public:string compressString(string S) {if (S.length()==0||S.length()==1) return S;string res="";char c=S[0];int l=S.length();int i,cnt=1;for (i=1;i<l;i++){if (S[i]==c){cnt++;}else{res+=c;res+=to_string(cnt);cnt=1;c=S[i];}if (res.length()>l) return S;}res+=c;res+=to_string(cnt);if (res.length()<l) return res;return S;} };int main(){Solution s;string tmp;while(cin>>tmp)cout<<s.compressString(tmp)<<endl;return 0; }總結
以上是生活随笔為你收集整理的面试题 01.06. 字符串压缩的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 窗外传来嬉闹声,我默默关上窗
- 下一篇: ubuntu清空回收站