暴力算法:o(n3)
//暴力算法 public class LongestPalindrome { public String longestPalindrome(String s) { String sub = null; int len = 0; for(int i = 0; i < s.length(); i ++) { for(int j = i; j < s.length(); j ++) { String tmp = s.substring(i,j+1); if(isPalindrome(tmp)&&tmp.length()>len) { sub = tmp; len = tmp.length(); } } } return sub; } public boolean isPalindrome2(String s) { int len = s.length(); if(len%2==1) { //这样写是很愚蠢的。因为既然知道了i是可以用总长度-i得到j,而不是让i和j同时滑动。 for(int i = 0, j = len-1; i < len/2&&j > len/2; i++,j-- ) { if(s.charAt(i)!=s.charAt(j)) return false; } return true; } else { for(int i = 0, j = len-1; i < len/2&&j > len/2; i++,j-- ) { if(s.charAt(i)!=s.charAt(j)) return false; } return true; } } public boolean isPalindrome(String s) { for(int i = 0; i < s.length()-1; i ++) { if(s.charAt(i) != s.charAt(s.length()-1-i)) return false; } return true; } public static void main(String[] args) { String s = "abc"; LongestPalindrome lp = new LongestPalindrome(); System.out.println(lp.isPalindrome(s)); System.out.println(lp.longestPalindrome(s)); } }
时间: 2024-10-10 17:42:31