LeetCode算法題之Count and Say

//問題描述
The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...


1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
Given an integer n, generate the nth sequence.


Note: The sequence of integers will be represented as a string.


//.................................................................//

//理解錯了題意,這寫的是輸入一個正整數N,則輸出他的第N個變形,其實這更具靈活性

class Solution
{
public:
    string countAndSay(int n)
    {
        if(n<=0)
            return "";
        if(n == 1)
            return "1";
        int sequenceLength = n-2;//此處很詭異啊,要是不減去2,下面的while循環會多循環2次,實際上很好理解,sequence是輾轉調用的
        stringstream itos;
        itos<<n;
        string sequence = "1" + itos.str(); //將數字轉爲字符串

        while(sequenceLength >0)
        {   //反覆調用
            sequence = printSequence(sequence);
            sequenceLength--;
        }
        return sequence;
    }
    string printSequence(string str)
    {
        string tempString;

        unsigned int i=0;
        int index=0;
        unsigned int j=0;
        while(j<str.length())
        {
            if(str[i] == str[j])
            {
                index++;
                if(j+1 == str.length())
                {  //最後一個數字的比較,下面的else語句將不再執行,只能在此處執行,否則將會把它漏掉
                    tempString = tempString + (char)(index+'0') +(char)str[i];
                    break;
                }
            }
            else
            {
                tempString = tempString + (char)(index+'0') +(char)str[i];
                i = j;//從下一個不同處開始計算某個數的連續存在次數,比如112211,數字1連續存在兩次後,
		      //變成2,此處的str[i]將變成2開始往下統計2的連續存在次數
                j--;  //j一定要退回一格,保持str[i]將變成2的同時str[j]還是2
                index = 0;
            }
            j++;
        }
        return tempString;
    }
};
//只是對1這個數而言,輸入一個整數n,輸出1的第n次變形,不過沒關係,用下面的
//代碼將上面理解錯誤的代碼中第一個while循環前的代碼替換掉即可AC

if(n<0)
    return "";
if(n == 1)
    return "1";
int sequenceLength = n-2;
string sequence = "11" ;

網上其他大神寫的比我的簡潔的多,沒辦法,笨啊!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章