public class Solution {
public String countAndSay(int n) {
// Start typing your Java solution below
// DO NOT write main() function
ArrayList<Character> current = new ArrayList<Character>();
current.add('1');
for (int i = 1; i != n; ++i)
current = next(current);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < current.size(); ++i)
sb.append(current.get(i));
return sb.toString();
}
ArrayList<Character> next(ArrayList<Character> current){
ArrayList<Character> tempList = new ArrayList<Character>();
Character temp = current.get(0);
int count = 1;
for (int i = 1; i < current.size()-1; ++i){
if (!current.get(i).equals(temp)){
add(tempList, count);
tempList.add(temp);
temp = current.get(i);
count = 1;
} else
count++;
}
if (current.size() > 1){
if (current.get(current.size()-1).equals(temp)) {
add(tempList, count+1);
tempList.add(temp);
} else {
add(tempList, count);
tempList.add(temp);
add(tempList, new Character('1'));
tempList.add(current.get(current.size()-1));
}
} else {
add(tempList, count);
tempList.add(temp);
}
return tempList;
}
ArrayList<Character> add(ArrayList<Character>temp, int i){
if (i < 10){
temp.add((char)(i+48));
return temp;
} else {
temp = add(temp, i / 10);
temp.add((char)(i % 10 + 48));
return temp;
}
}
}
原来自己写了一个函数add,而且int强制转换char是要加48的(一开始不知道,囧),然后还runtime error了。后来发现Character类有toChars()方法,改写了一下试试,结果发现完全不对。。。好像是这个方法必须是utf-16的编码= = 还是继续改原来的方法好了
public class Solution {
public String countAndSay(int n) {
// Start typing your Java solution below
// DO NOT write main() function
ArrayList<Character> current = new ArrayList<Character>();
current.add('1');
for (int i = 1; i != n; ++i)
current = next(current);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < current.size(); ++i)
sb.append(current.get(i));
return sb.toString();
}
ArrayList<Character> next(ArrayList<Character> current){
ArrayList<Character> tempList = new ArrayList<Character>();
Character temp = current.get(0);
int count = 1;
for (int i = 1; i < current.size()-1; ++i){
if (!current.get(i).equals(temp)){
add(tempList, count);
tempList.add(temp);
temp = current.get(i);
count = 1;
} else
count++;
}
if (current.size() > 1){
if (current.get(current.size()-1).equals(temp)) {
add(tempList, count+1);
tempList.add(temp);
} else {
add(tempList, count);
tempList.add(temp);
add(tempList, 1);
tempList.add(current.get(current.size()-1));
}
} else {
add(tempList, count);
tempList.add(temp);
}
return tempList;
}
ArrayList<Character> add(ArrayList<Character>temp, int i){
if (i < 10){
temp.add((char)('0' + i));
return temp;
} else {
temp = add(temp, i / 10);
temp.add((char)('0' + i % 10));
return temp;
}
}
}
吃饭去!!!