输入一个字符串,输出该字符串中对称的子字符串的最大长度。
2014-07-07 19:41
435 查看
/* * Q75题目:输入一个字符串,输出该字符串中对称的子字符串的最大长度。 * 比如输入字符串“google”,由于该字符串里最长的对称子字符串是“goog”,因此输出4。 */ public static void main(String[] args) { //String strs="google"; String strs="mnbvvvvbabbakkeaad"; int len=longestSymmtricalLength(strs); System.out.println(len); } /* * consider this string: * ..aAa..(A represents a string of any length) * if we already know 'A' is a palindrome, * we just need to test if the char before 'A' and that after 'A' are the same * if so,A=aAa now. * Do it again and again to find the result. * 考虑这个字符串: aAa .. ..(代表任意长度的字符串) 如果我们已经知道“A”是一个回文, 我们只需要测试,如果之前的“A”和之后的"A"是否相等 */ public static int longestSymmtricalLength(String str){ if(str==null||str.length()==0){ return -1; } int symLen=1; //总长度 char[] letter=str.toCharArray(); int strLen=str.length(); int curIndex=1; //索引位置 while(curIndex>0&&curIndex<strLen-1){ //odd symmetrical length,the 'pivot' char is letter[curIndex] <span style="white-space:pre"> </span>//奇对称的长度,letter[curindex] int i=curIndex-1; int j=curIndex+1; while(i>=0&&j<=(strLen-1)&&letter[i]==letter[j]){ i--; j++; } int newLen=j-i-1; if(newLen>symLen){ symLen=newLen; } //even symmetrical length,the 'pivot' chars are letter[curIndex] and letter[curIndex+1] //即使是对称的长度,letter[curIndex] 和letter[curIndex+1] //如果相等就再判断它的前后两项是否相等 i=curIndex; j=curIndex+1; while(i>=0&&j<=(strLen-1)&&letter[i]==letter[j]){ i--; j++; } newLen=j-i-1; if(newLen>symLen){ symLen=newLen; } curIndex++; } return symLen; } }
相关文章推荐
- 输入一个字符串,输出该字符串中对称的子字符串的最大长度。比如输入字符串“google”,由于该字符串里最长的对称子字符串是“goog”,因此输出4。
- 输入一个字符串,输出该字符串中对称的子字符串的最大长度。
- 输入一个字符串,输出该字符串中最大对称子串的长度
- 完美字符串 输入一个字符串S(S的长度 <= 10000),S中没有除字母外的其他字符。由你将1-26分配给不同的字母,使得字符串S的完美度最大,输出这个完美度。如dad 77
- 给你一个字符串,找出该字符串中对称的子字符串的最大长度。
- 写一函数,求一个字符串的长度。在main函数中输入字符串,并输出其长度。(指针)
- 找出字符串中对称的子字符串的最大长度(最长回文)
- 找出字符串中对称的子字符串的最大长度(最长回文)
- // 1、输入一个数组长度,动态创建数组,所有元素随机生成,输出元素中的最大值
- 找出字符串中对称的子字符串的最大长度(最长回文)
- 求字符串中对称的子字符串的最大长度
- 编程题:为了展示文件包含功能,输入一个字符串,输出其长度。
- 输入一个字符串,要求找出字符串中最大子串的长度
- 输入一个字符串,输出长度最长的单词
- (最长回文字串)字符串中对称的子字符串的最大长度
- 找出字符串中对称的子字符串的最大长度(最长回文)[No. 14]
- 02_对N个长度最长可达到1000的数进行排序、对给定的一个字符串,找出有重复的字符,并给出其位置、输入一系列整数,将其中最大的数挑出,并将剩下的数进行排序
- 输入字符串,找出相同且长度最长的子字符串,输出
- 输入一个字符串,输出长度最长的单词
- c语言输出字符串中最大对称子串长度的3种解决方案