415. 字符串相加【简单】
https://leetcode-cn.com/problems/add-strings/
- 模拟
class Solution {
public:
string addStrings(string num1, string num2) {
int len1 = num1.size();
int len2 = num2.size();
int add=0;
string ans="";
for(int i=0; i<max(len1,len2); i++)
{
int p1, p2;
if(i>=len1)
p1=0;
else
p1 = num1[len1-i-1] - '0';
if(i>=len2)
p2=0;
else
p2 = num2[len2-i-1] - '0';
int res=0;
res = (add + p1 + p2)%10;
add = (add+p1+p2)/10;
ans=(char)(res+'0')+ans;
}
if(add) ans =(char)(add+'0')+ans;
return ans;
}
};
20. 有效的括号【简单】
https://leetcode-cn.com/problems/valid-parentheses/
class Solution {
public:
bool isPair(char a, char b)
{
if(a=='('&&b==')')
return true;
if(a=='{'&&b=='}' )
return true;
if(a=='['&&b==']' )
return true;
return false;
}
bool isValid(string s) {
stack <char> tmp;
for(int i=0; i<s.length(); i++)
{
if(tmp.empty()||!isPair(tmp.top(),s[i]))
tmp.push(s[i]);
if(isPair(tmp.top(),s[i]))
tmp.pop();
}
if(!tmp.empty())
return false;
else return true;
}
};
括号生成【中等】
https://leetcode-cn.com/problems/generate-parentheses/
- dfs
class Solution {
public:
vector<string>ans;
void dfs(int left, int right, string cur, int n)
{
if(left>n||right>n)
return;
if(cur.size()==n*2&&left==n)
{
ans.push_back(cur);
return;
}
if(left>right)
dfs(left, right+1, cur+')', n);
dfs(left+1, right, cur+'(', n);
}
vector<string> generateParenthesis(int n) {
dfs(0,0,"", n);
return ans;
}
};
32. 最长有效括号【困难】
https://leetcode-cn.com/problems/longest-valid-parentheses/
- 先用stack检验,所有符合要求的s[i]置1,再遍历一遍找到最多连续的1
class Solution {
public:
int longestValidParentheses(string s) {
stack<int> stk;
vector<bool> pos(s.size(), 0);
for(int i=0; i<s.size(); i++)
{
if(s[i]=='(')
stk.push(i);
else if(s[i]==')')
{
if(!stk.empty())
{
s[stk.top()]=1;
s[i] = 1;
stk.pop();
}
}
}
int ans = 0;
int len = 0;
for(int i=0; i<s.size(); i++)
{
if(s[i]==1)
{
len++;
ans=max(ans, len);
}
else len=0;
}
return ans;
}
};