题目描述
在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).
解答:
public class Q_34 {
public int FirstNotRepeatingChar(String str) {
HashMap<Character, Integer> map = new HashMap<Character, Integer>();//存放字母在数组中的位置
int[] num = new int[52];//存放字母在字符串中的位置,若重复则改为-1
for (int m = 0; m < num.length; m++) {
num[m]=-1;
}
char[] arr = str.toCharArray();
int index = 0;//不同字母的个数
for (int i = 0; i < arr.length; i++) {
Integer add = map.get(arr[i]);
if (add == null) {
map.put(arr[i], index);
num[index] = i;
index++;
} else {
num[add] = -1;
}
}
for (int j = 0; j < num.length; j++) {
if (num[j] > -1) {
return num[j];
}
}
return -1;
}
public static void main(String[] args) {
System.out.println(new Q_34().FirstNotRepeatingChar("aAbaAb"));
}}

京公网安备 11010502036488号