您的位置:首页 > 其它

LeetCode OJ:Count and Say(数数)

2015-10-20 23:04 501 查看
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.

好奇怪的一道题目,意思是数(三)数(四).把数字用口头语言说出来,1就是1,2前面是1就是1一个(11),3前面2个1就是(21),然后是(1211),再是(111221)以此类推。。。 当时题目看了半天没看懂,又去别的地方查了下题目是什么意思才知道了:

class Solution {
public:
string countAndSay(int n) {
string curr = "";
if(n <= 0) return curr;
curr = "1";
for(int i = 1; i < n; ++i){
curr = convert(curr);
}
return curr;
}

string convert(const string & prev){
//string result = "";
stringstream result;
char last = prev[0];
int count = 0;
int sz = prev.size();
for(int i = 0; i <= sz; ++i){//注意是<=
if(prev[i] == last)
count++;
else{
result << count << last;
// result.append(count); 这里append无法实现,因为找不到itoa,很蛋疼,只能用stream来实现
// result.append(last);
last = prev[i];
count = 1;
}
}
return result.str();
}
};


下面是java版本的,用了双指针,方法和上面的还是有一点不一样的:

public class Solution {
public String countAndSay(int n) {
String s = String.valueOf(1);//很方便,直接就有类似itoa的api
for(int i = 1; i < n; ++i){
s = say(s);
}
return s;
}

public String say(String s){
int sz = s.length();
int p2 = 0, p1 = 0;
int count = 0;
String ret = new String("");
while(p1 < sz){
while(s.charAt(p1) == s.charAt(p2)){
p1++;
if(p1 == sz) //检查如果超过了长度就退出
break;
}
count = p1 - p2;
ret = ret + String.valueOf(count) + s.charAt(p2);
p2 = p1;//更新p2
}
return ret;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: