Created
August 24, 2013 10:05
-
-
Save Jimexist/6327243 to your computer and use it in GitHub Desktop.
Count And Say
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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