38. 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.
根據(jù)規(guī)律可以寫出后面的:
1. 1
2. 11
3. 21
4. 1211
5. 111221
6. 312211
7. 13112221
8. 1113213211
9. 31131211131221
10. 13211311123113112211
思路:
1.用2個串來替換存儲記錄result,tmp。
2.記錄當前值n,獲取當前值大連續(xù)長度m。
3.tmp串追加"m",再追加"n"。
代碼如下:
class Solution {
public:
string countAndSay(int n) {
if (--n < 0)
return "";
string result = "1";
string tmp; //臨時串
int step = 1;//步長
char cur; //當前元素
while (n)
{
cur = result[0];
for (int i = 0; i < result.size(); i++)
{
if ( i+1 < result.size() && result[i] == result[i + 1])
{
step++;
}
else
{
stringstream stepStream;
stepStream << step;
string stepStr = stepStream.str();
tmp.append(1,stepStr[0]);
tmp.append(1,cur);
step = 1;
cur = result[i + 1];
}
}
swap(result, tmp);
tmp = "";
n--;
}
return result;
}
};2016-08-10 17:24:26
另外有需要云服務器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內外云服務器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務器、裸金屬服務器、高防服務器、香港服務器、美國服務器、虛擬主機、免備案服務器”等云主機租用服務以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務可用性高、性價比高”等特點與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應用場景需求。
本文標題:leetCode38.CountandSay字符串-創(chuàng)新互聯(lián)
網(wǎng)站路徑:http://chinadenli.net/article2/cohgic.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供電子商務、網(wǎng)站導航、定制開發(fā)、微信公眾號、網(wǎng)站建設、動態(tài)網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經(jīng)允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)