0 题目来源
1 涉及到的知识点
字符串、
int到string的转换:
- C++11中string库有内置函数
**to_string()**
,功能为将指定的数字转化为string字符串,如下:
函数:
#include<string>
string to_string (int val);
string to_string (long val);
string to_string (long long val);
string to_string (unsigned val);
string to_string (unsigned long val);
string to_string (unsigned long long val);
string to_string (float val);
string to_string (double val);
string to_string (long double val);
示例:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string pi = "pi is " + to_string(3.141592);
cout << pi;
}
//输出
//pi is 3.141592
由于一些竞赛不允许使用C++11中的函数,因此可以采用如下方式,自定义to_string函数,实现int到string的转换,其中stringstream是位于sstream库中的字符串流:
#include <iostream>
#include <sstream>
using namespace std;
string to_string(int num)
{
stringstream ss;//定义一个ss流
string temp;
ss<<num;//将数字传递到ss流
ss>>temp;//将转换结果传到string
return temp;
}
int main()
{
string pi = "pi is " + to_string(3234524);
cout<<pi;
}
2 题目描述
字符串压缩。利用字符重复出现的次数,编写一种方法,实现基本的字符串压缩功能。比如,字符串aabcccccaaa会变为a2b1c5a3。若“压缩”后的字符串没有变短,则返回原先的字符串。你可以假设字符串中只包含大小写英文字母(a至z)。
3 样例
示例1:
输入:”aabcccccaaa”
输出:”a2b1c5a3”
示例2:
输入:”abbccd”
输出:”abbccd”
解释:”abbccd”压缩后为”a1b2c2d1”,比原字符串长度更长。4 提示
5 思路
本题较为简单,主要思路为对给定字符串进行遍历,当遇到新字符时,记录新字符,重新开始计数,并把之前所记录的数字和字符加入到新字符串中。在此过程中对新字符串和旧字符串的长度进行比较判断,然后返回指定的字符串。
6 代码
class Solution {
public:
string compressString(string S) {
string news;
char ch=S[0];
int tempcnt=1;
news+=ch;
for(int i=1;i<S.size();i++)
{
if(S[i]==ch)
tempcnt++;
else
{
news+=to_string(tempcnt);
ch=S[i];
news+=ch;
tempcnt=1;
}
if(news.size()>=S.size())
return S;
}
news+=to_string(tempcnt);
if(news.size()>=S.size())
return S;
else
return news;
}
};