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.
public class Solution { public String countAndSay(int n) { // Start typing your Java solution below // DO NOT write main() function String temp = String.valueOf(1); for(int i = 0 ; i < n-1 ; i++){ temp = cs(temp);//when update string make sure oldString = function(oldString) } return temp; } public String cs(String temp){ char[] chars= temp.toCharArray(); StringBuilder sb = new StringBuilder(); for(int i = 0 ; i < chars.length; i++){ int count = 1; while( i + 1 < chars.length && chars[i+1] == chars[i]){ count++; i++; //skip duplicated one } sb.append(String.valueOf(count)+String.valueOf(chars[i]));//do count and say } return sb.toString(); } }
learned: String.valueOf(1) return 1
public class Solution { public String countAndSay(int n) { if(n< 0 )return null; StringBuilder res = new StringBuilder("1"); while(n-->1){ StringBuilder temp = new StringBuilder(); int count = 1; for(int i = 1 ; i < res.length() ; i++){ if(res.charAt(i) == res.charAt(i-1)){ count++; } else{ temp.append(count); temp.append(res.charAt(i-1)); count = 1; } } temp.append(count); temp.append(res.charAt(res.length()-1)); res = temp; } return res.toString(); } }