3180-Java-2020-3-1

这里是不对的,因为需要保证中间没有两端,所以找到第一个首尾相同的就应该break

if(chars[i]==chars[j]&&j-i>len){
startIndex=i;
len=j-i;
break;
}

注意这里的写法,第一次遇到的时候需要给startindex初始化

if(chars[i]==chars[j]){
if(j-i>len||startIndex<0){
startIndex=i;
len=j-i;
}
break;
}

比较坑的是,单字符也算是满足题意的,也就是第一个字符

import java.io.*;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
class Main {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tokenizer = new StringTokenizer(reader.readLine());
String str = tokenizer.nextToken();
char[] chars = str.toCharArray();
int n = chars.length;
if(n==0){
System.out.print("");
return;
}
int startIndex = 0,len=0,max=0;
for(int i=0;i<n-1;i++){
for(int j=i+1;j<n;j++){
if(chars[i]==chars[j]){
if(j-i>len){
startIndex=i;
len=j-i;
}
break;
}
}
}
for(int i=startIndex;i<=startIndex+len;i++) System.out.print(chars[i]);
}
}

本文作者:YaosGHC

本文链接:https://www.cnblogs.com/yaocy/p/16872827.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   YaosGHC  阅读(20)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
💬
评论
📌
收藏
💗
关注
👍
推荐
🚀
回顶
收起