1+ //题号:387
2+ //给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
3+ //
4+ //
5+ //
6+ // 示例:
7+ //
8+ // s = "leetcode"
9+ //返回 0
10+ //
11+ //s = "loveleetcode"
12+ //返回 2
13+ //
14+ //
15+ //
16+ //
17+ // 提示:你可以假定该字符串只包含小写字母。
18+ // Related Topics 哈希表 字符串
19+ // 👍 364 👎 0
20+
21+
22+ public class FirstUniqueCharacterInAString {
23+ public static void main (String [] args ) {
24+ Solution solution = new FirstUniqueCharacterInAString ().new Solution ();
25+ solution .firstUniqChar ("loveleetcode" );
26+ }
27+ //leetcode submit region begin(Prohibit modification and deletion)
28+ class Solution {
29+ public int firstUniqChar (String s ) {
30+ /**
31+ * 也是统计字母出现次数,但是用map记录
32+ */
33+
34+ // if (s.isEmpty()) {
35+ // return -1;
36+ // }
37+ //
38+ // Map<Character, Integer> countMap = new HashMap<>(s.length());
39+ // for (int i = 0; i < s.length(); i++) {
40+ // countMap.put(s.charAt(i), countMap.getOrDefault(s.charAt(i), 0) + 1);
41+ // }
42+ //
43+ // for (int i = 0; i < s.length(); i++) {
44+ // char c = s.charAt(i);
45+ // //这里是只出现一次是1不是不出现0,好低级的错误
46+ // if (countMap.get(c) == 1) {
47+ // return i;
48+ // }
49+ // }
50+ //
51+ // return -1;
52+
53+
54+ /**
55+ * hash表底层是数组,在对于目标size已知的情况下可以直接用数组存储
56+ */
57+
58+ //代表'a'-'z'这些字符出现的次数
59+ int [] chars = new int [26 ];
60+
61+ for (int i = 0 ; i < s .length (); i ++) {
62+ char c = s .charAt (i );
63+ //这儿可以'z'-c也可以c-'a',是一样的,保证统一即可
64+ chars ['z' - c ]++;
65+ }
66+
67+ for (int i = 0 ; i < s .length (); i ++) {
68+ char c = s .charAt (i );
69+ if (chars ['z' - c ] == 1 ) {
70+ return i ;
71+ }
72+ }
73+
74+ return -1 ;
75+
76+
77+ /**
78+ * 运用HashMap+queue
79+ */
80+
81+ // if(s.length() == 0) return -1;
82+ // if(s.length() == 1) return 0;
83+ // Deque<Integer> queue = new LinkedList<>();
84+ //
85+ // HashMap<Character,Integer> set = new HashMap<>();
86+ //
87+ // for(int i= 0; i<s.length();i++){
88+ // if(!set.containsKey(s.charAt(i))){
89+ // set.put(s.charAt(i),1);
90+ // queue.offer(i);
91+ // }else {
92+ // set.put(s.charAt(i),set.get(s.charAt(i))+1);
93+ // if(!queue.isEmpty() && s.charAt(i) == s.charAt(queue.peek())){
94+ // while(!queue.isEmpty() && set.get(s.charAt(queue.peek())) !=1){
95+ // queue.poll();
96+ // }
97+ // }
98+ // }
99+ // }
100+ //
101+ // return (queue.isEmpty()) ? -1 : queue.poll();
102+
103+
104+
105+ }
106+ }
107+ //leetcode submit region end(Prohibit modification and deletion)
108+
109+ }
0 commit comments