算法分析与设计——LeetCode:5. Longest Palindromic Substring
2017-10-04 19:32
351 查看
题目
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.Example:Input: "babad"Output: "bab"
Note: "aba" is also a valid answer.
Example:Input: "cbbd"
Output: "bb"
class Solution { public: string longestPalindrome(string s) { } };
思路
遍历字母,以每一个字母为中心,同时遍历前后相对应的字母,判断是否相等。如果不相等则停止遍历。但是这样只能找出aba这样的,找不出abba,abbbba这样的,所以在前面先用两个while循环将所有与中心相同的字母包含进来。
代码
class Solution { public: string longestPalindrome(string s) { int size = s.size(); if (size <= 1) { return s; } int start = 0, max = 1; for (int i = 1; i < size; i++) { int start_ = i-1, end_ = i+1; int current = 1; while (start_ >= 0 && s[start_] == s[i]) {//忽略所有相同的字母,如aaa,aa start_--; current++; } while (end_ <= size && s[end_] == s[i]) {//忽略相同字母 end_++; current++; } while (start_ >= 0 && end_ >= 0) { if (s[start_] == s[end_]) { start_--; end_++; current += 2; } else { start_++; break; } } if (start_ < 0) {//避免aa这样的字符串使start_小于0 start_++; } if (current > max) { max = current; start = start_; } } return s.substr(start, max); } };
相关文章推荐
- [算法分析与设计] leetcode 每周一题: Set Matrix Zeroes
- [算法分析与设计] leetcode 每周一题: 80. Remove Duplicates from Sorted Array II
- [算法分析与设计] leetcode 每周一题: 467. Unique Substrings in Wraparound String
- 算法分析与设计——LeetCode Problem.538 Convert BST to Greater Tree
- 算法分析与设计——LeetCode:62. Unique Paths
- 算法分析与设计丨第二周丨LeetCode(4)——Maximum Subarray(Easy)
- 算法分析与设计丨第六周丨LeetCode(10)——Best Time to Buy and Sell Stock(Easy)
- [算法分析与设计] leetcode 每周一题: 420. Strong Password Checker
- 算法分析与设计——LeetCode Problem.33 Search in Rotated Sorted Array
- 算法分析与设计——LeetCode:136. Single Number
- 算法分析与设计——LeetCode Problem.598 Range Addition II
- 算法分析与设计丨第十八周丨LeetCode(21)——Binary Tree Maximum Path Sum(Hard)
- 算法分析与设计——LeetCode:101. Symmetric Tree
- 算法分析与设计课程(19):【leetcode】Ugly Number II
- 算法分析与设计——LeetCode Problem.18 4Sum
- 算法分析与设计——LeetCode Problem.35 Search Insert Position
- [算法分析与设计] leetcode 每周一题: Surrounded Regions
- [算法分析与设计] leetcode 每周一题: 053. Maximum Subarray
- 算法分析与设计——LeetCode Problem.670 Maximum Swap
- 算法分析与设计——LeetCode Problem.653 Two Sum IV - Input is a BST