有效的括号
像这样的题一般都会想到辅助栈
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;
}
};