面试题:给你一串字符串,找出其中最长的对称子序列。 例如:(输入:qwedfggfdekl ~> 输出:edfggfde)
思路:分为两步,对于给定的字符串s先求出其逆序字符串s1,然后比较s和s1的最长相同子串。
1 public class LongestSymmetryString{
2
3
4 public static String getLongestSymmetryString(String s){
5 String reverseString = new StringBuffer(s).reverse().toString();
6 List<String> resultStrList = new ArrayList<>();
7 int max = 0;
8 int start, end;
9 for(int i=0; i<s.length(); i++)
10 {
11 start = i;
12 for(end = s.length(); ; end--){
13 if(start >=end) break;
14 String substr = s.substring(start, end);
15 int temp = end - start;
16 if(temp>max && reverseString.contains(substr))
17 {
18
19 resultStrList.add(substr);
20
21 max = temp;
22 }
23
24 }
25 }
26 int index = resultStrList.size();
27 return resultStrList.get(index-1);
28 }
29
30 public static void main(String[] args) {
31 // TODO Auto-generated method stub
32 Scanner sb = new Scanner(System.in);
33 while(sb.hasNextLine())
34 {
35 s = sb.nextLine();
36 if(s == null)
37 {
38 System.out.println(0);
39 return ;
40 }
41 System.out.println(getLongestSymmetryString(s));
42 }
43 }
44 }
浙公网安备 33010602011771号