您的位置:首页 > 其它

判断一个字符串是否为回文,以及求一个字符串中最长回文串

2014-07-18 14:06 246 查看
<pre name="code" class="java"><pre name="code" class="java">package com.four;

public class huiFe1 {
public static void main(String args[]) {
String str = "x1234774321sdjh";
// String str = "x212sdjh";
String result = "";
for (int i = 0; i < str.length(); i++) {
result = check(result, str, i - 1, i + 1);
result = check(result, str, i, i + 1);
}
System.out.println(result);
if (result == "") {
System.out.println("这不是个回文串");
} else {
System.out.println(str + "中的" + result + "是一个回文");
}
}

public static String check(String result, String str, int start, int end) {
while (start >= 0 && end < str.length()) {
if (str.charAt(start) != str.charAt(end)) {
break;
}
start--;
end++;
}
start++;
end--;
if (start != end) {
String temp = str.substring(start, end + 1);
if (temp.length() > result.length()) {
result = temp;
}
}
return result;
}

}




                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: