Thursday, October 3, 2013

Count and Say@leetcode

刷题必备书籍Cracking the Coding Interview: 150 Programming Questions and Solutions 

简历:The Google Resume: How to Prepare for a Career and Land a Job at Apple, Microsoft, Google, or any Top Tech Company
算法学习书籍:Introduction to Algorithms
编程珠玑:Programming Pearls (2nd Edition)
C++ 学习:The C++ Programming Language, 4th Edition
经典操作系统书籍,龙书:Operating System Concepts
创业:The Start-up of You: Adapt to the Future, Invest in Yourself, and Transform Your Career

Count and Say


AC Rate: 439/1647
My Submissions
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.
就是string的操作,那个tmp string做中间记录,一个n用于数,还有count,思路不难,要注意的就是string的操作,这里
str.append(str, char)是不行的,char不能append到string上,因为string 是const,而char是variable, append只能
用于string之间,而char添加直接用 str = str + char 加号就行了。

换上自己风格的代码看上去就是舒服些。。。
class Solution {
public:
string countAndSay(int n) {
string res = "1", tmp;
for(int i=1; i<n; i++){
int j=0;
while(j<res.size()){
int count = 0;
char cur = res[j];
while(j<res.size()&&res[j]==cur){
count ++;
j ++;
}
tmp.append(std::to_string(count));
if(j==0) tmp.append("1");
else
tmp += res[j-1];
}
res.clear();
res = tmp;
tmp.clear();
}
return res;
}
};
view raw countandsay hosted with ❤ by GitHub
class Solution {
public:
string countAndSay(int n) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(n<=0) return NULL;
string res="1";
while(n-->1)
{
string tmp;
int count = 1;
for(int i=1; i<res.size(); i++)
{
if(res[i]==res[i-1])
{
count++;
}
else
{
char tmp1='0'+count;
tmp= tmp+tmp1;
tmp= tmp+res[i-1];
count=1;
}
}
char tmp1 = '0'+count;
tmp= tmp+ tmp1;
tmp= tmp+res[res.size()-1];
res = tmp;
}
return res;
}
};
view raw Count and Say hosted with ❤ by GitHub

No comments:

Post a Comment

Leetcode 316. Remove Duplicate Letters

 这道题表面问的是如何删除重复,实际在问如何从多个字符选取一个保留,从而让整个字符串按升序排列。那么策略就是对于高顺位的字符比如‘a',就要选靠前位置的保留,而低顺位字符如’z'则应该尽量选取靠后位置保留。 算法大概思路:每看到一个字符,我们要决定是否保留 1. ...