java 38. Count和Say.java

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 38. Count和Say.java相关的知识,希望对你有一定的参考价值。

class Solution(object):
    
    def countAndSay(self, n):
        """
        :type n: int
        :rtype: str
        """
        
        
            
        baseStr = "1";
        res = [];
        res.append("1");
        
        while(n > 1):
            count = 1;
            temp = ""
            for i in range(1, len(baseStr)): # start from index 1 
                if baseStr[i] == baseStr[i - 1]:
                    count += 1;
                elif baseStr[i] != baseStr[i - 1]:
                    temp += str(count) + baseStr[i - 1];
                    count = 1;
            temp += str(count) + baseStr[-1]; # add the last element of the baseStr
            res.append(temp);
            n -= 1;
            baseStr = temp;
        
        return res[-1];
        
        
        
"""
#####
TESTCASES:
Input:
1
2
3
4
5
6

Output:
"1"
"11"
"21"
"1211"
"111221"
"312211"
"""
        
public class Solution {
    public String countAndSay(int n) {
        String baseStr = "1";
        List<String> res = new ArrayList<String>();
        res.add(baseStr);
        while(n > 1){
            int count = 1;
            StringBuilder temp = new StringBuilder();
            for(int i = 1; i < baseStr.length(); i++){
                if(baseStr.charAt(i) == baseStr.charAt(i - 1)){
                    count++;
                } else {
                    temp.append(count);
                    temp.append(baseStr.charAt(i - 1));
                    count = 1;
                }
            }
            temp.append(count);
            temp.append(baseStr.charAt(baseStr.length() - 1));
            res.add(temp.toString());
            n--;
            baseStr = temp.toString();
        }
        
        return res.get(res.size() - 1);
    }
}

以上是关于java 38. Count和Say.java的主要内容,如果未能解决你的问题,请参考以下文章

java 38. Count和Say.java

java 38. Count和Say.java

java 38. Count和Say.java

java 38. Count和Say.java

[LeetCode] 38. Count and Say 计数和读法

leetcode 38 Count and Say