Simple 4ms Java Solution


  • 0
    A

    Use the helper function and treat input as String. In each iteration from 1 to n, count contiguous digits and append that to result with count first and then the corresponding digit. We can use StringBuilder for this instead of String concatenation so that we don't create new String objects every time. Here's the code

    class Solution {
        public String countAndSay(int n) {
            String result = "1";
            for(int i = 1; i < n; i++) {
                result = generateSequence(result);
            }
            
            return result;
        }
        
        private String generateSequence(String input) {
            StringBuilder sb = new StringBuilder();
            char ch = input.charAt(0);
            int count = 1;
            for(int i=1; i < input.length(); i++) {
                if(ch == input.charAt(i)) {
                    count++;
                } else {
                    sb.append(count).append(ch);
                    count = 1;
                    ch = input.charAt(i);
                }
            }
            
            sb.append(count).append(ch);
            return sb.toString();
        }
    }
    
    

Log in to reply
 

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