LeetCode_OJ【5】Longest Palindromic Substring

来源:互联网 发布:快手录歌都用什么软件 编辑:程序博客网 时间:2024/04/28 05:30

Given a string S, find the longest palindromic substring inS. You may assume that the maximum length ofS is 1000, and there exists one unique longest palindromic substring.

这道题还是比较简单的,主要运用分支限界的方法,首先定义isPalindrome函数,如果是回文串就返回回文串的长度,否则返回-1.在搜索过程中不断比较当前搜索空间是否大于已经找出的最长串的长度max,大于则继续搜索,否则提前结束搜索。


public class Solution {public int isPalindrome(String s,int start,int end){        int low = start;int high = end;while(start < end){    if(s.charAt(start ++) != s.charAt(end --))    return -1;}return high - low + 1;}public String longestPalindrome(String s) {int max = 1;int low=0,high=0;for(int i = 0 ; i < s.length() - max ; i++){for(int j= s.length() -1 ; j -i +1 > max ; j--){if(isPalindrome(s, i, j) > max){max = isPalindrome(s, i, j);low = i;high = j;}}}return s.substring(low, high+1);}}



0 0
原创粉丝点击