java code using String type


  • 0
    T

    we use String type to achieve this question.
    class Solution {

    public String count(String str){
        int count = 1;
        String newStr = "";
        for(int m = 1; m < str.length(); m++){
                if(str.charAt(m) == str.charAt(m-1))
                    count++;
                else{
                    newStr =newStr + count+ "" +str.charAt(m-1);
                    count = 1;
                }
          }
        newStr = newStr + count + "" + str.charAt(str.length() - 1);
        return newStr;
    }
    public String countAndSay(int n) {
        String str = "1";
        for(int i = 1; i < n; i++)
            str = count(str);
        return str;
    }
    

    }


Log in to reply
 

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