Accepted Java Solution with explanation


  • 0
    T

    '''
    if( n==1 ){
    return "1";
    }
    // Let the start string be "1"
    StringBuilder result = new StringBuilder("1");

        // Loop through n-1 times
        for( int i=2; i<=n; i++ ){
            StringBuilder temp_str = new StringBuilder("");
            // Loop through the string result, get repeated (or single count) and the corresponding character
            // and form a new string, assign it to result and loop again
            for( int j=0;j<result.length();j++){
                int count = 1;
                while( j+1<result.length() && result.charAt(j+1)==result.charAt(j) ){
                    j++;
                    count++;
                }
                temp_str = temp_str.append(count).append(result.charAt(j));
                count = 1;
            }
            // Assign the temp_str to result for another loop
            result = temp_str;
    
            
        }
        return result.toString();
    

    '''


Log in to reply
 

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