Skip to content

Instantly share code, notes, and snippets.

@daifu
Created May 9, 2013 18:36
Show Gist options
  • Save daifu/5549534 to your computer and use it in GitHub Desktop.
Save daifu/5549534 to your computer and use it in GitHub Desktop.
Count and Say
/*
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.
Algorithm:
1. it is very straight forward since it needs to loop through the previous
string to find out for the next
*/
public class Solution {
public String countAndSay(int n) {
// Start typing your Java solution below
// DO NOT write main() function
if(n == 1) return "1";
String str = "1";
for(int i = 2; i <= n; i++) {
str = countAndSayHelper(str);
}
return str;
}
public String countAndSayHelper(String str) {
StringBuffer sb = new StringBuffer();
for(int i = 0; i < str.length(); i++) {
char cur = str.charAt(i);
if(i < str.length() - 1 && cur == str.charAt(i+1)) {
int count = 1;
int j = i+1;
for(; j < str.length(); j++) {
if(cur != str.charAt(j)) break;
count++;
}
i = j-1; // update the index
sb.append(count);
sb.append(cur);
} else {
sb.append(1);
sb.append(cur);
}
}
return sb.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment