字符串中的匹配之递归

Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome.
Example 1:
Input: "aba"
Output: True

Example 2:
Input: "abca"
Output: True

AC代码：

class Solution {
public:
bool isHuiwen(string& s,int l,int r){
while (l < r){
if (s[l] != s[r])
return false;
l++;
r--;
}
return true;
}
bool validPalindrome(string s) {
bool res;
int l, r;
l = 0;
r = s.size()-1;
while (l < r){
if (s[l] != s[r])
return isHuiwen(s, l+1, r) || isHuiwen(s, l, r-1);
l++;
r--;
}
return isHuiwen(s, 0, s.size()-1);
}
};


Given a string containing only three types of characters: '(', ')' and '*', write a function to check whether this string is valid. We define the validity of a string by these rules:

1. Any left parenthesis '(' must have a corresponding right parenthesis ')'.
2. Any right parenthesis ')' must have a corresponding left parenthesis '('.
3. Left parenthesis '(' must go before the corresponding right parenthesis ')'.
4. '*' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string.
5. An empty string is also valid.

Example 1:
Input: "()" Output: True
Example 2:
Input: "(*)" Output: True
Example 3:
Input: "(*))" Output: True

AC代码:

class Solution2 {
public:
int lll;

bool check(string& s,int start,int lcnt,int rcnt){
int l, r;
l = lcnt;
r = rcnt;
for (int i = start; i < lll; ++i){
if (s[i] == '(')
l++;
if (s[i] == ')')
r++;
if (r > l)
return false;
if (s[i]=='*'){
return check(s, i+1, l+1, r) ||
check(s, i+1, l, r+1) ||
check(s, i+1, l, r);
}
}
return l == r;
}

bool checkValidString(string s) {
lll = s.size();
return check(s, 0, 0, 0);
}
};


low代表左括号可能出现的下界，high代表左括号可能出现的上界。

• 当遇到一个(时，low++,high++;
• 当遇到一个)时，low--,high--;
• 当遇到一个*时，low--,high++; （即我们既可以把*看成(也可以看成)
• 注意的是，下界一旦小于0直接返回false代表右括号太多了， 但是上界我们得人为保证其值>=0，因为*可以被视作空白或右括号(例如"(**")。但是最后结束的时候必须保证上界为0，如果最后上界不为0就是左括号太多了。

class Solution {
public:
bool checkValidString(string s) {
int lower = 0, upper = 0;
for (char c : s) {
if (c=='(') {
lower++;
upper++;
} else if (c==')') {
lower--;
upper--;
} else { // * encountered
lower--;
upper++;
}
lower = max(lower, 0);
if (upper<0) // unmatched ')' found in the middle of string
return false;
}
return lower==0;
}
};

posted @ 2017-09-17 23:44 ohazyi 阅读(...) 评论(...) 编辑 收藏