My code:
public class Solution {
public String countAndSay(int n) {
if (n <= 0)
return null;
else if (n == 1)
return "1";
int count = 1;
String result = "1";
while (count < n) {
int begin = 0;
int i = begin + 1;
String temp = "";
while (i < result.length()) {
if (result.charAt(i) == result.charAt(i - 1))
i++;
else {
temp += Integer.toString(i - begin) + result.charAt(begin);
begin = i;
i++;
}
}
temp += Integer.toString(i - begin) + result.charAt(begin);
result = temp;
count++;
}
return result;
}
public static void main(String[] args) {
Solution test = new Solution();
System.out.println(test.countAndSay(2));
}
}
My test result:
这次作业比较有趣。可以科普下什么叫做 count and say number sequence.
https://en.wikipedia.org/wiki/Look-and-say_sequence
也没有什么技术含量。还是简单的扫描字符串。
**
总结: String, scan
**
Anyway, Good luck, Richardo!
My code:
public class Solution {
public String countAndSay(int n) {
if (n <= 0)
return null;
StringBuilder s = new StringBuilder(String.valueOf(1));
for (int i = 1; i < n; i++) {
s = helper(s);
}
return s.toString();
}
private StringBuilder helper(StringBuilder s) {
if (s == null || s.length() == 0)
return null;
StringBuilder ret = new StringBuilder();
int counter = 1;
char pre = s.charAt(0);
for (int i = 1; i < s.length(); i++) {
char curr = s.charAt(i);
if (curr != pre) {
ret.append(String.valueOf(counter) + pre);
counter = 1;
pre = curr;
}
else {
counter++;
}
}
if (counter != 0) {
ret.append(String.valueOf(counter) + pre);
}
return ret;
}
}
一开始拿String做的,排名在 30%左右。换成,StringBuilder之后,排名变成了70%
题目本身并没有什么难度。
今天把zappos的OA做了。感觉不是很难。但是也是提前看了题目之后才说出这样的话的。现在看到string,palindrome,parentheses。。。第一反应就是,DP, GREEDY
其实完全不用这么紧张的。
palindrome 用DP
valid parentheses可以用dp,也可用stack
Anyway, Good luck, Richardo!
My code:
public class Solution {
HashMap<Integer, String> map = new HashMap<Integer, String>();
public String countAndSay(int n) {
if (n <= 0) {
return null;
}
String s = "1";
for (int i = 1; i < n; i++) {
s = transform(s);
}
return s;
}
private String transform(String s) {
StringBuilder ret = new StringBuilder();
int begin = 0;
int end = 1;
while (end <= s.length()) {
if (end < s.length() && s.charAt(end) == s.charAt(end - 1)) {
end++;
}
else {
int diff = end - begin;
ret.append(diff);
ret.append(s.charAt(begin));
begin = end;
end++;
}
}
return ret.toString();
}
}
reference:
https://discuss.leetcode.com/topic/14543/straightforward-java-solution/2
这道题目我犯傻比了。
我的想法是:
比如输入 Integer 11
我先写个函数,将Integer -> String
11 -> "Two 1"
再写个函数,将String -> Integer
"Tow 1" -> 21
然后我再拿 21 输入第一个函数,以此类推,拿到第n个数
其实完全不用这么复杂。因为我们最后需要输出的,不是 "Two 1"
而是 "21"
所以,直接把 "11" -> "21"
这样,一下就变简单题了。
Anyway, Good luck, Richardo! -- 09/20/2016