标签:遍历 function tar har stp mat sub you example
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"
class Solution { public String longestPalindrome(String s) { if(s == null || s.length() < 1) { return ""; } int start = 0, end = 0; for(int i = 0; i < s.length(); i++) { int len1 = helper(s, i, i); int len2 = helper(s, i, i + 1); int len = Math.max(len1, len2); if(len > end - start) { start = i - (len - 1) / 2; end = i + len / 2; } } return s.substring(start, end + 1); } private int helper(String s, int left, int right) { int l = left, r = right; while(l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; } return r - l - 1; } }
5. Longest Palindromic Substring - Medium
标签:遍历 function tar har stp mat sub you example
原文地址:https://www.cnblogs.com/fatttcat/p/10317768.html