对简单题重拳出击的一天

有效的括号

在这里插入图片描述

像这样的题一般都会想到辅助栈

class Solution {
public:
    bool isValid(string s) {
        unordered_map<char,int> m{{'(',1},{'[',2},{'{',3},{')',4},{']',5},{'}',6}};
        
        stack<char> stk;
        bool flag = true;
        for(char c:s){

            int i = m[c];
            if(i>=1&&i<=3) stk.push(c);
            else if(!stk.empty()&&i==m[stk.top()]+3){
                stk.pop( );
            }else {flag = false; break;}

        }
        if(!stk.empty()) flag = false;  //防止最后一个是左括号而for循环判断错误
        return flag;
    }
};

C++确实有点费力啊



class Solution:
    def isValid(self, s):
        while '{}' in s or '()' in s or '[]' in s:
            s = s.replace('{}', '')
            s = s.replace('[]', '')
            s = s.replace('()', '')
        return s == ''

如果s=="{[(){}]}",那么依次置空的是(){}[]{}






数字转换为十六进制数

在这里插入图片描述

class Solution {
public:
    string toHex(int num) {
        if(num==0) return "0";

        unsigned int n = num;
        string numToHex = "0123456789abcdef";
        string res = "";
        while(n!=0){
            res = numToHex[n&15] + res;
            n = n>>4;
        }
        return res;
    }
};






计数二进制子串

在这里插入图片描述
看了大佬的思路,果然不是我这凡人能想像的

class Solution {
public:
    int countBinarySubstrings(string s) {
        int len = s.length();
        vector<int> counts;
        int ans=0;
        int i=0;
        int j=0;
        while(i<len){
            if(s[i]=='0'){
            
                for(j=i+1;s[j]=='0'&&j<len;++j){}
                
            }else{
            
                for(j=i+1;s[j]=='1'&&j<len;++j){}
                
            }
            
			counts.push_back(j-i);
            i=j;

        }

        for(int k=1;k<counts.size();++k){
            ans += std::min(counts[k-1],counts[k]);
        }

        return ans;

    }
};

这里可以用一个变量记录上一次的j-i,然后直接在while循环中比较,累加结果

class Solution {
public:
    int countBinarySubstrings(string s) {
        int len = s.length();
        
        int ans=0;
        int last=0;
        int count=0;
        int i=0;
        int j=0;
        while(i<len){
            if(s[i]=='0'){
                
                for(j=i+1;s[j]=='0'&&j<len;++j){}
                
            }else{
                for(j=i+1;s[j]=='1'&&j<len;++j){}
                
            }
            
            count = j-i;
            ans += std::min(last,count);
            last = count;
            i=j;

        }

        return ans;


    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值