Header Ad

Leetcode Count and Say problem solution

In this Leetcode Count and Say problem solution we have given a positive integer n, return the nth term of the count-and-say sequence.

leetcode count and say problem solution


Problem solution in Python.

class Solution(object):
    def countAndSay(self, n):
        s0 = '1'
        for i in range(1, n):
            s1, k = '', 1
            for j in range(1, len(s0)):
                if s0[j-1] == s0[j]: k += 1
                else: s1, k = s1 + str(k) + s0[j-1], 1
            s1 += str(k) + s0[-1]
            s0 = s1
        return s0



Problem solution in Java.

public String countAndSay(int n) {
    if(n == 0) return "";
    String res = "1";
   for(int i = 1; i <n; i++){
       String s = res;  res="";  
       int count = 1;// attention for the logic
       char pre = s.charAt(0);
       for(int j = 1; j < s.length(); j++){
            if(s.charAt(j) == pre)
                count++;
            else{
                res += count+""+pre;
                pre = s.charAt(j);
                count = 1;
            }
      }
      res += count +""+ pre;
   }
   return String.valueOf(res);
}


Problem solution in C++.

class Solution {
public:
    string countAndSay(int n) {
        string temp="1";
        string ans="";
        if(n==1)return temp;
        for(int i=2;i<=n;i++)
        {
            char value=temp[0];
            int count=1;
            ans="";
            for(int j=1;j<temp.size();j++)
            {
                if(temp[j]==value)count++;
                else 
                {
                    ans+=count+'0';
                    ans+=value;
                    count=1;
                    value=temp[j];
                }
            }
            ans+=count+'0';
            ans+=value;
            temp=ans;
        }
        return ans;
    }
};


Problem solution in C.

char* fromLast(char* last) {
    char *s = last;
    int count;
    int index = 0;
    char *result = (char*) malloc(2 * strlen(last));
    while(*s != '\0') { 
        count = 1;
        while(*s == *(s+1)) {   
            count++;
            s++;
        }
        result[index++] = count + '0';
        result[index++] = *(s);
        s++;
    }
    result[index] = '\0';
    return result;
}
char* countAndSay(int n) {
    if(n == 1) 
        return "1";
    return fromLast(countAndSay(n-1));
}


Post a Comment

0 Comments