您的位置:首页 > 其它

Leetcode|Count and Say

2015-07-03 08:42 330 查看
The count-and-say sequence is the sequence of integers beginning as follows:

1, 11, 21, 1211, 111221, …

1 is read off as “one 1” or 11.

11 is read off as “two 1s” or 21.

21 is read off as “one 2, then one 1” or 1211.

Given an integer n, generate the nth sequence.

Note: The sequence of integers will be represented as a string.

题目很简单,就是构造一个寻找next值的函数。

可以中间转换过程为字符串的转换或者先是数组的转换,最后变为字符串。

解法1:字符串转换

采用stringsteam ss实现数字和字符到字符串的转换;(0ms)

还可以直接用string 的+实现。(4ms)

string getnext(string s){
stringstream ss;
int start=0,end=0;
int count=0;
for(int i=0;i<=s.size();i++){
if(i<s.size()&&s[i]==s[start]){
count++;
end=i;
}else{
ss<<count;//实现过程
ss<<s[start];
count=1;
start=end=i;
}
}
return ss.str();
}
string countAndSay(int n) {
string s;
if(n==0){
return "";
}
if(n==1){
return "1";
}
s="1";
for(int k=2;k<=n;k++){
s=getnext(s);
}
return s;
}


采用+的方式:(4ms)(这种方法效率还是挺低的)

string getnext(string s){
string res;
int start=0,end=0;
int count=0;
for(int i=0;i<=s.size();i++){
if(i<s.size()&&s[i]==s[start]){
count++;
end=i;
}else{
res+=to_string(count)+s[start];//提出这一行
count=1;
start=end=i;
}
}
return res;
}


如果把那一行改为这个:res+=char(count+’0’)+s[start];

+可以加字符串也可以是单字符(char)。但是这样写有问题。

相当于先计算后面两个字符相加。

string的+的使用是一个很有趣的问题。

做个实验:

string s;
s=s+"1"+'1';
cout<<s;//输出 "11"(s=s+'1'+"1";)效果一样


string s;
s+='1'+'1';
cout<<s;//输出“b"
cout<<'1'+'1';//输出98(int)


如果我好好看看string的类的定义应该会明白的。

解法2:数组转换(0ms)

string vectostr(vector<int> s){
stringstream ss;
for(int i=0;i<s.size();i++){
ss<<s[i];
}
return ss.str();
}
vector<int> getnext(vector<int>& s){
vector<int> res;
int start=0,end=0;
int count=0;
for(int i=0;i<=s.size();i++){
if(i<s.size()&&s[i]==s[start]){
count++;
end=i;
}else{
res.push_back(count);
res.push_back(s[start]);
count=1;
start=end=i;
}
}
return res;
}
string countAndSay(int n) {
string res;
if(n==0){
return "";
}
if(n==1){
return "1";
}
vector<int> s(1,1);
for(int k=2;k<=n;k++){
s=getnext(s);
}
res=vectostr(s);
return res;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: