leetcode笔记

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();
	}
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值