LeetCode刷题日记(Day3)

Problem 5. 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.

  • 解题思路:
    回文子串,即正序和倒序输出结果都一样的字符串。例如字符串“sabad”的回文子串就是“aba”。本题需要求的是给定字符串的最长回文子串。
    用动态规划的方法求解。令 dp[i][j] 表示从字符 s[i] 到 s[j] 构成的字符串是否是回文子串,是则赋值为1,否则为0。则存在以下两种转移状态:

    1. 若 s[i] == s[j],则只要 dp[i+1][j-1] == 1,则s [i] 到 s[j] 构成回文子串;若 dp[i+1][j-1] == 0,则 s[i] 到 s[j] 不构成回文子串。
    2. 若 s[i] != s[j],则 s[i] 到 s[j] 一定不构成回文子串。
    3. 边界情况是 dp[i][i] = 1, dp[i][i+1] = (s[i] ==s[i+1])? 1:0。
  • 时间复杂度分析:
    使用动态规划求解,可使得算法的时间复杂度降为O(n^2)。

  • 代码实现

class Solution {
public:
    string longestPalindrome(string s) {
        int len = s.length(), longest = 1, start = 0;
        int dp[1000][1000] = {0};
        for (int i = 0; i < len; ++i){
            dp[i][i] = 1;
            if (i < len-1 && s[i] == s[i+1]){
                start = i;
                dp[i][i+1] = 1;
                longest = 2;
            }
        }
        for (int L = 3; L <= len; ++L){
            for (int i = 0; i + L -1 < len; ++i){
                int j = i + L -1;
                if (s[i] == s[j] && dp[i+1][j-1] == 1){
                    dp[i][j] = 1;
                    longest = L;
                    start = i;
                }
            }
        }
        return s.substr(start, longest);
    }
};

7. Reverse Integer

  • 题目描述
    Given a 32-bit signed integer, reverse digits of an integer.

  • 解题思路:
    对输入的x,使用/和%操作即可得到结果,要注意防止出现int溢出。

  • 代码实现

class Solution {
public:
    int reverse(int x) {
        long res = 0;
        while(x != 0){
            res = res *10 + x%10;
            x /= 10;
        }
        return (res < INT_MIN || res > INT_MAX)? 0: res;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_36348299/article/details/88343507