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

120 阅读2分钟

面试题 01.06. 字符串压缩

面试题 01.06. 字符串压缩

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

示例1:
输入:“aabcccccaaa”
输出:“a2b1c5a3”
示例2:
输入:“abbccd”
输出:“abbccd”
解释:“abbccd"压缩后为"a1b2c2d1”,比原字符串长度更长。
提示:
字符串长度在[0, 50000]范围内。

其中 t o    S t r i n g to\,\,String toString的作用是返回对某一对象类型的字符串值.例如 I n t e g e r . t o S t r i n g ( ) Integer.toString() Integer.toString()是将 I n t e g e r Integer Integer的整形对象的数值返回成字符串形式,等同于 " " + I n t e g e r "" + Integer ""+Integer

可能会出现error: ‘to_string’ was not declared in this scope的情况,to_string是 C + + 11 C++11 C++11引入的新功能,旧版本编译器可能不支持它,所以要给编译器加上 “ C + + 11 ” “C++11” “C++11”编译支持, D e v C + + Dev C++ DevC++编译器:在菜单栏点开 T o o l s − > C o m p i l e    O p t i o n s Tools -> Compile\,\,Options Tools−>CompileOptions,加上圈住的编译指令即可让编译器支持 C + + 11 C++11 C++11的标准。(参考链接)
在这里插入图片描述 C++

#include<iostream>
#include<string>
using namespace std;
class Solution {
public:
    string compressString(string S) {//S为字符串 
        string res;
        int i = 0, j = 0;
        while (i < S.length()) {
            while (S[i] == S[j]) j ++;//j是遍历到的index 
            res += S[i] + to_string(j - i);//to_string(j - i)把数字字符化 
//toString的作用是返回对某一对象bai类型的字du符串值。
//例如Integer.toString()是将Integer的整形对象的数zhi值返回成字符串形式,等同dao于 "" + Integer
            i = j;
        }
        return (res.length() >= S.length()) ? S : res;//大于原数组返回原数组,否则返回带数字对的现数组 
    }
};


int main(void)
{
	Solution s;//一个Solution类 
	string str="aaaabbbbbbcc";
	string out =s.compressString(str);
	cout<<out<<endl;
	system("pause");
	return 0; 
} 

相关链接:

Leecode官网
java编程里面to String有什么作用?
error: ‘to_string’ was not declared in this scope