回文是指正着读和倒着读,结果一些样,比如abcba或abba。
听说有三种方法:
法一:就是我这种呆子能想到的,遍历啊,但时间复杂度应该是O^3,而且算法过程复杂,要是没我的思路清晰,头脑敏捷,不骄不躁,就换下一个方法吧O(∩_∩)O
import java.io.BufferedReader;
import java.io.IOException;import java.io.InputStreamReader;import java.util.ArrayList;import java.util.Scanner; public class Five{ public static void longestPalindrome(String s) { ArrayList<Integer> List = new ArrayList<Integer>(); String temp="0"; for(int i=0;i<s.length();i++) { char item1=s.charAt(i); temp=temp+item1; for(int j=i+1;j<s.length();j++) if(s.charAt(j)!=item1) temp=temp+s.charAt(j); else { temp=temp+s.charAt(j); int loc = temp.indexOf("0"); String newStr=temp.substring(0,loc); List.add(newStr); } } String LongestSubstring = null; for(int k=1;k<List.size();k++) { System.out.println((String) List.get(k-1)); if(((String) List.get(k-1)).length()<((String) List.get(k)).length()) LongestSubstring=((String) List.get(k)); else LongestSubstring=((String) List.get(k-1)); } System.out.println(LongestSubstring); } public static void main(String args[]) throws IOException{ //BufferedReader rd = new BufferedReader(new InputStreamReader(System.in)); System.out.println("请输入一个字符串:"); Scanner scanner = new Scanner(System.in); String line = scanner.nextLine(); longestPalindrome(line); }}法二:动态规划。。参考别人的,自己肯定是想不到啦
import java.io.BufferedReader;
import java.io.IOException;import java.io.InputStreamReader;import java.util.ArrayList;import java.util.Scanner; public class Five_third{ public static String longestPalindrome(String s) { if (s == null || s.length() == 0) return ""; int n = s.length(); int max = 0, start = 0, end = 0; boolean[][] c = new boolean[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { c[i][j] = i >= j ? true : false; } } //c[i][j] for (int j = 1; j < n; j++) { for (int i = 0; i < j; i++) { if (s.charAt(i) == s.charAt(j) && c[i+1][j-1]) { c[i][j] = true; if (j - i + 1 > max) { max = j - i + 1; start = i; end = j; } } else c[i][j] = false; } } return s.substring(start, end+1); } public static void main(String[] args){ System.out.println("请输入一个字符串:"); Scanner scanner = new Scanner(System.in); String line = scanner.nextLine(); String ins=longestPalindrome(line); System.out.println(ins); } }