前言
最近在小伙伴的讨论中,突然对LeetCode上面的题感兴趣,大家不约而同开始研究简单算法,于是把最近遇到的题总计一下,后面复习也可以再看看,对于题目的解法,很多不是出自我自己的思路,都是我的小伙伴们集思广益的结果,在这里先谢过啦!
题目
- 简单描述:
用程序验证规律,1,11,21,1211,111221,...
问题详情
Count and Say.
解法:
1. 解法一: 递归+循环
public String countAndSay(int n) {
if (n == 1) {
return "1";
}
String tempStr = countAndSay(n - 1);
List<String> nums = new ArrayList<String>();
List<String> values = new ArrayList<String>();
String current = tempStr.charAt(0) + "";
int currentNum = 1;
for (int i = 1; i < tempStr.length(); i++) {
String temp = tempStr.charAt(i) + "";
if (current.equals(temp)) {
currentNum++;
} else {
nums.add(currentNum + "");
values.add(current);
current = temp;
currentNum = 1;
}
}
nums.add(currentNum + "");
values.add(current);
StringBuilder resoult = new StringBuilder();
for (int i = 0; i < nums.size(); i++) {
resoult.append(nums.get(i));
resoult.append(values.get(i));
}
return resoult.toString();
}
2. 解法二:双重for循环
public String countAndSay(int n) {
String str = "1";
for (int i = 0; i < n-1; i++) {
String num = "";
char strart = str.charAt(0);
int count = 0;
char[] strings = str.toCharArray();
for (char j : strings) {
if (strart != j) {
num += "" + count + strart;
strart = j;
count = 0;
}
count++;
}
num += "" + count + strart;
str = num;
}
return str;
}
3. 解法三 :双重递归
public static String countAndSay(int n) {
if (n == 1) {
return "1";
}
String tempStr = countAndSay(n - 1);
return getString(tempStr);
}
private static String getString(String tempStr) {
if (tempStr.length() == 1) {
return "1" + tempStr;
}
char start = tempStr.charAt(0);
for (int i = 1; i < tempStr.length(); i++) {
if (start != tempStr.charAt(i)) {
return "" + i + start + getString(tempStr.substring(i));
}
}
return "" + tempStr.length() + start;
}
总结
文章中的解法,仅仅代表我及小伙伴们自己的思路,各路大神有更好的解法,请多多指教!