您的位置:首页 > 其它

对称子字符串的最大长度

2011-01-26 23:03 288 查看
题目:输入一个字符串,输出该字符串中对称的子字符串的最大长度。比如输入字符串“google”,由于该字符串里最长的对称子字符串是“goog”,因此输出4。
public class Test46 {

/**
* @param args
*/
public static int f(String str) {

int length = str.length();
int max = 1;
int s1 = 0;
int s2 = 1;
int s3 = 0;
int low;
int high;
int len;
for (int i = 0; i < str.length(); i++) {

if (i == 0) {
if (str.charAt(i) == str.charAt(i + 1)) {
max = 2;
}
continue;
}

low = i - 1;
high = i;

while (low >= 0 && high <= length - 1) {

if (str.charAt(low) == str.charAt(high)) {
s1 += 2;
}
low--;
high++;
}

low = i - 1;
high = i + 1;

while (low >= 0 && high <= length - 1) {
if (str.charAt(low) == str.charAt(high)) {
s2 += 2;
}
low--;
high++;
}

low = i;
high = i + 1;

while (low >= 0 && high <= length - 1) {
if (str.charAt(low) == str.charAt(high)) {
s3 += 2;
}
low--;
high++;
}
System.out.println(i + " s1 = " + s1);
System.out.println(i + " s2 = " + s2);
System.out.println(i + " s3 = " + s3);

len = (s1 > s2 ? s1 : s2) > s3 ? (s1 > s2 ? s1 : s2) : s3;

max = max > len ? max : len;

s1 = 0;
s2 = 1;
s3 = 0;
}
return max;
}

public static void main(String[] args) {
// TODO Auto-generated method stub

String str = "gogogle";
System.out.println(f(str));
}

}

参考资料:http://zhedahht.blog.163.com/blog/static/25411174201063105120425/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: