Count and Say


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;
}
}
}

吃饭去!!!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值