38. Count and Say
Description
描述:https://leetcode.com/problems/count-and-say/description/
题意:从1开始,从左至右,对数字计数,将个数和对应的数字连接(计数并读出)并作为下一个数。
Solution: (Java)
class Solution {
public String countAndSay(int n) {
String result = "1";
String temp = "";
char c = ' ';
int count = 0;
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < result.length(); j++) {
if (c != result.charAt(j)) {
if (count != 0) {
temp = temp + count + String.valueOf(c);
}
c = result.charAt(j);
count = 1;
} else
count++;
}
temp = temp + count + String.valueOf(c);
result = temp;
temp = "";
c = ' ';
count = 0;
}
return result;
}
}
思路
- 读懂题意即可,从左至右,对数字计数,将个数和对应的数字连接(计数并读出)并作为下一个数;
- 也可以用递归的方法,或者使用 StringBuilder 来进行字符串的链接,可能会减少一些时间。