Friday, April 4, 2014

Count and Say @LeetCode

The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
Given an integer n, generate the nth sequence.
Note: The sequence of integers will be represented as a string.
package leetcode;
import java.util.ArrayList;
/**
* Solution: Not Hard, Just some operation on String. just use oldString to store the last value.
* The way I use ArrayList is waste of space. No need to store all values.
*
* Problem is not easy to understand, see Reference.
* Reference: http://www.careercup.com/question?id=4425679
*
* @author jeffwan
* @date Apr 4, 2014
*/
public class CountAndSay {
public String countAndSay(int n) {
String oldString = "1";
while (--n > 0) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < oldChars.length; i++) {
int count = 1;
while ((i + 1) < oldChars.length && oldString.charAt(i) == oldString.charAt(i + 1)) {
count++;
i++;
}
sb.append(String.valueOf(count) + String.valueOf(oldString.charAt(i)));
}
oldString = sb.toString();
}
return oldString;
}
// My version -- use ArrayList to store all sequence. just need to code findNext out. Not hard.
public String countAndSay2(int n) {
if (n <= 0) {
return "";
}
ArrayList<String> result = new ArrayList<String>();
result.add("1");
for (int i = 1; i < n; i++) {
result.add(findNext(result.get(i)));
}
return result.get(n - 1);
}
public String findNext(String str) {
String result = "";
int count = 1;
for (int i = 0; i < str.length() - 1; i++) {
if (str.charAt(i) != str.charAt(i + 1)) {
result += String.valueOf(count) + str.charAt(i);
count = 1;
continue;
}
count++;
}
result += String.valueOf(count) + str.charAt(str.length() - 1);
return result;
}
}

No comments:

Post a Comment