外觀數列


外觀數列」是一個整數序列,從數字 1 開始,序列中的每一項都是對前一項的描述。前五項如下:

1. 1
2. 11
3. 21
4. 1211
5. 111221
1 被讀作  "one 1"  ("一個一") , 即 11。
11 被讀作 "two 1s" ("兩個一"), 即 21。
21 被讀作 "one 2",  "one 1" ("一個二" ,  "一個一") , 即 1211。

給定一個正整數 n(1 ≤ n ≤ 30),輸出外觀數列的第 n 項。

注意:整數序列中的每一項將表示為一個字符串。

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/count-and-say
解題思路:要得到第n行的字符串,要先得到第n-1行的字符串。通過遍歷第n-1行的字符串,得到每個字符出現的次數count和該字符ch,那么第n行的新字符串就由count和ch構成。如果直接遞歸,必然超時。因此,可以通過在同一個函數中從第一行或第二行的字符串開始用循環推導出余下行的字符串即可。

1.我的代碼:

class Solution {
    public String countAndSay(int n) {
        if(n==1){
            return "1";
        }
        else if(n==2){
            return "11";
        }
        else{
            String str="11";
            for(int i=2;i<n;i++){
                StringBuilder sb=new StringBuilder();
                for(int j=0;j<str.length();j++){
                    char ch1=str.charAt(j);
                    int count=1;
                    for(int k=j+1;k<str.length();k++){
                        char ch2=str.charAt(k);
                        if(ch1==ch2){
                            count++;
                            j=k;
                        }
                        else {
                            break;
                        }
                    }
                    sb.append(count).append(ch1);
                }
                str=sb.toString();
            }
            return str;
        }
    }
}
2.題解代碼:

public String countAndSay(int n) {
String str = "1";
for (int i = 2; i <= n; i++) {
StringBuilder builder = new StringBuilder();
char pre = str.charAt(0);
int count = 1;
for (int j = 1; j < str.length(); j++) {
char c = str.charAt(j);
if (c == pre) {
count++;
} else {
builder.append(count).append(pre);
pre = c;
count = 1;
}
}
builder.append(count).append(pre);
str = builder.toString();
}

return str;
}

作者:pphdsny
鏈接:https://leetcode-cn.com/problems/count-and-say/solution/38-bao-shu-java-xun-huan-by-pphdsny/
來源:力扣(LeetCode)

我的代碼和題解代碼的差別在於,多了一個for循環。但其實這一for循環是沒有必要增加的。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM