对称子字符串的最大长度

对称子字符串的最大长度
题目:输入一个字符串,输出该字符串中对称的子字符串的最大长度。
比如输入字符串“ google”,由于该字符串里最长的对称子字符串是“ goog”,因此输出 4。
分析:可能很多人都写过判断一个字符串是不是对称的函数,这个题目可以看成是该函数的

加强版。

/**
 * 对称子字符串的最大长度
题目:输入一个字符串,输出该字符串中对称的子字符串的最大长度。
比如输入字符串“ google”,由于该字符串里最长的对称子字符串是“ goog”,因此输出 4。
分析:可能很多人都写过判断一个字符串是不是对称的函数,这个题目可以看成是该函数的
加强版。
 * @author wycheng
 *
 */
public class SymmLongest {
	public static int subSolution(String str){
		if(null == str){
			return 0;
		}
		if(str.length() == 1){
			return 1;
		}
		int count = 0;
		int p =0;
		int q=str.length()-1;
		while(p<q){
			if(str.charAt(p)==str.charAt(q)){
				count+=2;
				p++;
				q--;
			}else{
				q--;
				count=0;
			}
		}
		if(p==q){
			++count;
		}else{
			
		}
		return count;
	}
	
	public static int solution(String str){
		int maxLen = 0;
		int tmpLen = 0;
		for(int i=0;i<str.length();i++){
			for(int j=str.length();j>=0;j--){
				if(i<j){
					String strTmp = str.substring(i, j);
					tmpLen = subSolution(strTmp);
				}
				if(tmpLen > maxLen){
					maxLen=tmpLen;
				}
				
				if(j-i<maxLen){
					break;
				}
			}
		}
		return maxLen;
	}
	public static void main(String[] args) {
		System.out.println(solution("google"));
	}
}


你可能感兴趣的:(对称子字符串的最大长度)