Skip to content

Instantly share code, notes, and snippets.

@Jimexist
Created August 24, 2013 10:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jimexist/6327243 to your computer and use it in GitHub Desktop.
Save Jimexist/6327243 to your computer and use it in GitHub Desktop.
Count And Say
import java.util.*;
public class Solution {
public String countAndSay(int n) {
List<Integer> i = new ArrayList<Integer>();
i.add(1);
while (--n > 0) {
i = say(i);
}
StringBuilder sb = new StringBuilder();
for (int ii : i) {
sb.append(ii);
}
return sb.toString();
}
public List<Integer> say(List<Integer> input) {
final List<Integer> result = new ArrayList<Integer>();
int last = input.get(0);
int count = 1;
for (int i=0; i<input.size()-1; ++i) {
if (input.get(i+1) != last) {
result.add(count);
result.add(last);
count=1;
last=input.get(i+1);
} else {
count++;
}
}
result.add(count);
result.add(last);
return result;
}
public List<Integer> encode(int i) {
List<Integer> result = new ArrayList<Integer>();
while (i > 0) {
result.add(i % 10);
i = i / 10;
}
java.util.Collections.reverse(result);
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment