Count and Say(when not equal and string builder append)
1,11,21,1211,111221
1 => one 1 => 11
11=> two 1=>21
21=> one two one one=> 1211
so its String.value(count)+"1 or 2" and convert it to int
Given an integer n, generate the nth sequence
like n = 2=> "11"
like n =4 =>"1211"
2. Implementation
Q1: how to count?
A1: an array count array count[value-1], count[0] =? , count[1]=?
Q1: how to iterate?
A1: top-down approach, for loop, return a string, int next = "1", int[] count = new int[2]
str.charAt(i), i < length(), count[(int)(str.charAt(i)-'0')-1]++;
// NOTE: every index correspond to an number
for (int i =2 ; i <= n; i++ ) // i=1 already appear pre = "1"
// NOTE: when equal, count is already two
int count =1;
for (int j =1 ;j < pre.length; i++) {
for (int j =1 ;j < pre.length; i++) {
//count[((int)(pre.charAt(j)-'0')) - 1]++;
if ( pre.charAt(j) == pre.cahrAt(j-1) )
count++;
// NOTE: if all the same or the last count
res.append(count);
res.append( res.charAt(pre.length()-1) );
pre = res.toString();
(M) Encode and Decode Strings
// Time:O(n*string length), Space:O(string length) stringbuilder public String countAndSay(int n) { //vlaidate teh input if ( n <= 0 ) return ""; String pre = "1";// 1st //for ( int i = 2 ; i < n; i++) // NOTE: every index correspond to an number for (int i =2 ; i <= n; i++ ) { //int[] count = new int[2]; // NOTE: when equal, count is already two int count =1; // NOTE: StringBuilder res = new StringBuilder(); //for (int j = 0 ; j < pre.length; j++) // NOTE: contiguous counts for (int j =1 ;j < pre.length; i++) { //count[((int)(pre.charAt(j)-'0')) - 1]++; if ( pre.charAt(j) == pre.cahrAt(j-1) ) count++; else { res.append(count); res.append(pre.charAt(j-1)); count =1; //reset } } //StringBuilder sb = new StringBuilder(); //if (count[0] != 0) //{ // sb.append(count[0]); // sb.append(1); //} //if (count[1] != 0) //{ // sb.append(count[1]); // sb.append(2); //} // NOTE: if all the same or the last count res.append(count); res.append( res.charAt(pre.length()-1) ); pre = res.toString(); } return pre; }3. Similar Ones
(M) Encode and Decode Strings
No comments:
Post a Comment