My Simple Java Solution


  • 4
    T
    public class Solution {
        public String countAndSay(int n) {
            if(n <= 0) return "";
            String init = "1";
            while(n-- > 1){
                init = say(init);
            }
            return init;
        }
        public String say(String str){
            if(str.length() < 1) return "";
            int count = 1;
            StringBuilder sb = new StringBuilder();
            char c = str.charAt(0);
            if(str.length() == 1){
                sb.append(count);
                sb.append(c);
                return sb.toString();
            }
            for(int i = 1; i < str.length(); i ++){
                if(str.charAt(i) == str.charAt(i - 1)){
                    count ++;
                }else{
                    sb.append(count);
                    sb.append(c);
                    count = 1;
                    c = str.charAt(i);
                }
            }
            sb.append(count);
            sb.append(c);
            return sb.toString();
        }
    }
    

    A simple java solution, say function is to return the next item in the sequence using the previous item.


  • 0
    T

    Hi, nice solution but for a large n, this causes Exception in thread "main" java.lang.OutOfMemoryError: Java heap space. For example, try n = 100.


Log in to reply
 

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