Simple Java, recursive


  • 0
    S
    public String countAndSay(int n) {
            if(n == 1) {
                return "1";
            }
            
            String prev = countAndSay(n-1);
            int count = 1;
            char prevChar = prev.charAt(0);
            StringBuilder result = new StringBuilder();
            
            for(int i = 1; i<prev.length(); i++) {
                if(prev.charAt(i) == prevChar) {
                    count++;
                } else if(prev.charAt(i) != prevChar) {
                   result.append(String.valueOf(count)+prevChar);
                   prevChar = prev.charAt(i);
                   count = 1;
                }
            }
            
            result.append(String.valueOf(count)+prev.charAt(prev.length()-1));
            return result.toString();
        
        }

Log in to reply
 

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