使用JAVA实现寻找一个字符串中最长的对称字符串:
如输入字符"121a123321",返回"123321". 实现代码:
1 import org.junit.Test; 2 3 public class MirroString { 4 public String getMaxMirroString(String s){//找出字符串中最长的对称字符串的方法 5 6 if (s!=null||s.length() != 0) { 7 int length = s.length(); 8 9 for (int strLength = length; strLength>1; strLength--){//控制检验对称字符串的长度 10 int rightIndex = strLength-1;//作为右索引 11 12 for(int leftIndex = 0; leftIndex <= s.length() - strLength; leftIndex++,rightIndex++){//左右索引右移 13 int couple = s.substring(leftIndex,rightIndex+1).length()/2;//字符串整除2的值 14 int count = 0;//数字符串中对称字符的对数 15 16 for(int l = leftIndex,r = rightIndex; l<r; l++,r--) {//从外向内检索字符串左右字符 17 if (s.charAt(l) == s.charAt(r)) { 18 count++;//字符串中对称的字符对数 19 } 20 } 21 22 if (count == couple){//判断字符串是否完全对称 23 return s.substring(leftIndex,rightIndex+1); 24 } 25 } 26 } 27 return "无对称字符"; 28 }else return "字符串为空"; 29 } 30 31 @Test 32 public void Test(){//验证 33 MirroString mS = new MirroString(); 34 System.out.println( mS.getMaxMirroString("abadefgfe")); 35 System.out.println(mS.getMaxMirroString("11221454")); 36 System.out.println(mS.getMaxMirroString("21221")); 37 } 38 39 }
某次笔试题中迟迟无法做出,现在终于稀里糊涂做出来.希望有大神给出好的解法.