题目:在一个由小写英文字母(a-z)组成的字符串中,查找最短子串,其头尾字母相同。输出最左边的该类子串。
思路:暴力解法,但是有两个Wrong answe ,想知道为啥呀
import java.util.*;
class text04 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
Map<String,Integer> map = new HashMap<>();
int maxLength=0;// 存放最大长度
String answer="";// 存放结果
int position = 0;// 存放字符开始下标
for(int i=0;i<s.length();i++){
char title = s.charAt(i);
// 暴力求最长字符串
for(int j=i+1;j<s.length();j++){
char end = s.charAt(j);
if(title!=end){
continue;
}else{
map.put(s.substring(i,j+1),i);
break;
}
}
}
// 遍历集合中所求得的字符串
for (String s1 : map.keySet()) {
if(s1.length()>maxLength) {// 求最长字串
maxLength = s1.length();
answer=s1;
position=map.get(s1);
}
else if(s1.length()==maxLength){// 如果字串长度相同 比较首字符开始的位置
if(map.get(s1)>position){
continue;
}else{// 输出最左边 难道我理解错 最左的意思了嘛
answer=s1;
position=map.get(s1);
}
}
else {
}
}
System.out.println(answer);
}
}