Non recursive and readable Java solution


  • 0
    P

    Just a easy approach. First of all, loop n-1 time starting from 1th string "1". Each loop use previous result string as char array,then empty the result string and count the same chars and then add into the result string.

    public class Solution {
    public String countAndSay(int n) {
        if(n ==1) return "1";
        
        if(n <= 0) return null;
        
        StringBuilder resultStr = new StringBuilder();
        resultStr.append("1");
        
        // loop n-1 time
        while(n>1){
            // convert str to char array
            char[] currentStr = resultStr.toString().toCharArray();
    
            // count the number of the same char
            int counter=0;
            
            // reset the resultStr
            resultStr.setLength(0);
           
            char prevChar = currentStr[0];
            for(int j =0 ; j<currentStr.length;j++){
                // make sure previous char and current char are the same
                if(currentStr[j]==prevChar){
                    counter++;
                    
                }else{
                    resultStr.append(String.valueOf(counter));
                    resultStr.append(String.valueOf(prevChar));
                    prevChar = currentStr[j];
                    counter=1;
                   
                    
                }
            }
            // Don't forget to add the lastest part
            resultStr.append(String.valueOf(counter));
            resultStr.append(String.valueOf(prevChar));
           
            n--;
        }
        
        return resultStr.toString();
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.