Longest Palindromic Substring
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: “babad”
Output: “bab”
Note: “aba” is also a valid answer.
Example 2:
Input: “cbbd”
Output: “bb”
思路(动态规划):
- 创建二维数组dp[i][j],行列值为字符串的size(),其中i,j分别代表字符串的起始和终止索引。dp[i][j] = 1代表字符串s[i][j]为回文。
- 分为三种情况:
- dp[i][i] = 1,即单个字符为回文
- dp[i][i+1]=1,两个字符相同为回文
- dp[i][j+len]=1,len = 3,4,5… - 遍历每个len的基础上,遍历 i - > j 的字符,并判断否s[i]== s[j] && dp[i+1][j-1] == 1
代码实现:
class Solution {
public:
string longestPalindrome(string s) {
int length = s.size();
int max = 0;
int start =0;
vector< vector<int>> dp(length,vector<int>(length));
for (int i=0; i<length; i++){
dp[i][i] = 1;
if (s[i]==s[i+1]){
dp[i][i+1]=1;
max = 2;
start = i;
}
}
for (int len=3;len<length;len++){
for(int i=0;i+len<length;i++){
int j = i+len;
if(s[i]==s[j] && dp[i+1][j-1]){
dp[i][j]=1;
max = len;
start = i;
}
}
}
return s.substr(start, start+max);
}
};
Valid Parentheses(有效的括号)
Given a string containing just the characters ‘(’, ‘)’, ‘{’, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Example 1:
Input: “()”
Output: true
Example 2:
Input: “()[]{}”
Output: true
Example 3:
Input: “(]”
Output: false
Example 4:
Input: “([)]”
Output: false
Example 5:
Input: “{[]}”
Output: true
思路(利用栈):
- 遍历字符串,遇到左括号压入栈,遇到右括号的话取top()出来比较(通过ASCII比较),比较符合的话pop出栈。
- 特殊情况:字符串为奇数;栈为空就遇到右括号。
#include<stack>
#include<string>
class Solution {
public:
bool isValid(string s) {
stack<int> st;
if (s.length() % 2 != 0){
return false;
}
for (int i = 0; i < s.length(); i++){
if (s[i] == '}' || s[i] == ']' || s[i] == ')' ){
if (st.empty()) return false;
else if(s[i]-st.top()==1 || s[i]-st.top()==2){ // ASCII {}相差2
st.pop();
}
}
else st.push(s[i]);
}
return st.empty();
}
};