Last active
February 27, 2019 02:05
-
-
Save qiaoxu123/27655a2aa15ad0fb76b125975f4fe064 to your computer and use it in GitHub Desktop.
> 对数字数量进行计算,并据此生成新的字符串的过程 主要难点在于循环的把握,以及数字转字符串函数的使用 代码二也是同样的思路,但是通过算法进行了优化,减少了循环进行了性能提升
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Runtime: 4 ms, faster than 100.00% | |
//Memory Usage: 8.6 MB, less than 95.80% | |
class Solution { | |
public: | |
string countAndSay(int n) { | |
string res = "1",cur = "1"; | |
while(--n){ | |
char ch = res[0]; | |
int count = 0; | |
cur = ""; | |
for(int i = 0;i < res.size();i++){ | |
if(ch == res[i]) | |
count++; | |
else{ | |
cur += count + '0'; | |
cur += ch; | |
ch = res[i]; | |
count = 1; | |
} | |
} | |
cur += count + '0'; | |
cur += ch; | |
res = cur; | |
} | |
return res; | |
} | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Runtime: 8 ms, faster than 75.88% | |
//Memory Usage: 8.7 MB, less than 83.18% | |
class Solution { | |
public: | |
string countAndSay(int n) { | |
if(n == 0) return ""; | |
string res = "1"; | |
while(--n){ | |
string cur = ""; | |
for(int i = 0;i < res.size();i++){ | |
int count = 1; | |
while((i + 1 < res.size()) && (res[i] == res[i + 1])){ | |
count++; | |
i++; | |
} | |
cur += to_string(count) + res[i]; | |
} | |
res = cur; | |
} | |
return res; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment