import java.util.Arrays; //因为字符串只有字母组成所以可以利用哈希表 public class Solution { public int FirstNotRepeatingChar(String str) { int[] hx = new int[26]; //存储每个字符出现的次数 int[] x = new int[26]; int[] index = new int[26]; //存储每个字符出现的最后一次的下标 int[] dex = new int[26]; int ret = -1; for (int i = 0; i < str.length(); i++){ if (str.charAt(i) >= 'A' && str.charAt(i) <= 'Z'){ x[str.charAt(i) - 'A']++; dex[str.charAt(i) - 'A'] = i; } else{ hx[str.charAt(i) - 'a']++; index[str.charAt(i) - 'a'] = i; } } for (int i = 0; i < 26; i++){ if (hx[i] == 1){ if ((ret == -1) || (index[i] < ret && ret != -1)){ ret = index[i]; } } else if (x[i] == 1){ if ((ret == -1) || (dex[i] < ret && ret != -1)){ ret = dex[i]; } } } return ret; } }