算法-字符串处理-在一个字符串中第一个不重复的字符
原文链接:https://blog.csdn.net/C_X666666/article/details/84335111
-
public class StringOneOne {
-
public static void main(String[] args) {
-
System.out.print("请输入:");
-
//输入一个字符串
-
Scanner input = new Scanner(System.in);
-
String str = input.next();
-
//调用判断第一个不重复字符串的方法
-
int index = firstNoRepetitionChar(str);
-
//判断返回的索引,如果是-1代表没有不重复的
-
if(index == -1){
-
System.out.println("没有不重复的字符");
-
return;
-
}
-
//根据返回的索引,输出第一个不重复的字符
-
System.out.println("第一个不重复的字符是:"+str.charAt(index));
-
}
-
private static int firstNoRepetitionChar(String str){
-
//创建一个HashMap对象,前面用来存字符,后面用来存每个字符出现的次数
-
Map<Character,Integer> map = new HashMap<>();
-
//循环遍历字符串的每一个字符,将每个字符以及其出现的次数存入map集合
-
for(int i =0;i<str.length();i++){
-
char c = str.charAt(i);
-
if(map.containsKey(c)){
-
map.put(c, map.get(c)+1);
-
}else{
-
map.put(c, 1);
-
}
-
}
-
//在此遍历字符串,根据每个字符出现的次数来判断是否不重复
-
//如果次数等于1,证明不重复,返回此字符索引
-
//如果没有,返回 -1 为FLAG,以证明没有不重复的字符
-
for(int i = 0;i<str.length();i++){
-
char c = str.charAt(i);
-
if(map.get(c)==1){
-
return i;
-
}
-
}
-
return -1;
-
}
-
}