2021-05-13字符串太难了!

38.

第二种反而效率更高一些!

class Solution {
public:
    string countAndSay(int n) {
        return helper("1", n, 1);
    }

    string helper(string s, int n, int index){
        if(index == n){
            return s;
        } 
        int nums =1;
        string s1;
        for(int i=0; i< s.size(); i++){
            if(i<s.size()-1 && s[i] == s[i+1]){
                nums++;
                continue;
            }
            s1 += to_string(nums) + s[i];
            nums = 1;
        }
        return helper(s1, n, index+1);
    }
};

class Solution {
public:
string ans;
    string countAndSay(int n) {
        helper("1", n, 1);
        return ans;
    }

    void helper(string s, int n, int index){
        if(index == n){
            ans = s;
            return;
        } 
        int nums =1;
        string s1;
        for(int i=0; i< s.size(); i++){
            if(i<s.size()-1 && s[i] == s[i+1]){
                nums++;
                continue;
            }
            s1 += to_string(nums) + s[i];
            nums = 1;
        }
        helper(s1, n, index+1);
    }
};

//不要总加,也有减的、
class Solution {
public:
    string countAndSay(int n) {
        if(n == 1) return "1";
        string pre = countAndSay(n-1), ans;
        int count = 1;
        for(int i = 0; i < pre.size(); i++)
        {
            if(pre[i] != pre[i + 1])
            {
                ans += (count + '0');
                ans += pre[i];
                count = 0;
            }
            count++;
        }
        return ans;
        
    }
};

443.不会!

错了,如何删一个??

class Solution {
public:
    int compress(vector<char>& chars) {
        int num =1;
        int index =0;
        for(int i=0; i<chars.size(); i++){
            if(i<chars.size()-1 && chars[i]==chars[i+1]){
                if(num >2) chars.erase(chars[i]);
                index = i;
                num++;
                continue;
            }
            if(num != 1) chars[index +1] = to_string(num);//出现超过一次,

        }
        return chars.size();
    }
};


class Solution {
public:
    int compress(vector<char>& chars) {
        int rear = -1, l = 0, r = 0;
        while(r < chars.size()){
            l = r;
            while(r < chars.size() && chars[l] == chars[r])r++;            
            chars[++rear] = chars[l];
            if(r - l == 1) continue;
            for(const auto& x:to_string(r - l)) chars[++rear] = x;
        }
        return rear + 1;
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值