码迷,mamicode.com
首页 > 其他好文 > 详细

(leetcode) countandsay

时间:2015-05-07 11:44:09      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:

class Solution {
public:
    string calcuate(string s)
    {
        string result;
        char pre = s[0];
        int cnt = 1;
        for(int i =1;i < s.length();i++)
        {
            if(s[i] == pre)
            {
                cnt++;
            }
            else
            {
                char tmp = cnt+‘0‘;
                result += tmp + pre;
                pre = s[i];
                cnt=1;
            }
            
        }
		char tmp = cnt + ‘0‘;
		result += tmp + pre;

        return result;
    }
    string countAndSay(int n) {
        string ret;
        ret = "1";
        int j = 1;
        while(j < n)
        {
            ret = calcuate(ret);
            j++;
        }
        return ret;
    }
};

  上面方法错误 原因是由于使用 result += tmp +pre;这个操作

下面是修改后的代码:
class Solution {
public:
    string calcuate(string s)
    {
        string result;
        char pre = s[0];
        int cnt = 1;
        for(int i =1;i < s.length();i++)
        {
            if(s[i] == pre)
            {
                cnt++;
            }
            else
            {
                char tmp = cnt+‘0‘;
                result = result + tmp + pre;
                pre = s[i];
                cnt=1;
            }
            
        }
		char tmp = cnt + ‘0‘;
		result = result+ tmp + pre;

        return result;
    }
    string countAndSay(int n) {
        string ret;
        ret = "1";
        int j = 1;
        while(j < n)
        {
            ret = calcuate(ret);
            j++;
        }
        return ret;
    }
};

  

(leetcode) countandsay

标签:

原文地址:http://www.cnblogs.com/chdxiaoming/p/4484019.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!