387. 字符串中的第一个唯一字符

转载自Leet Code

题目描述

给定一个字符串 s ,找到 它的第一个不重复的字符,并返回它的索引 。 如果不存在,则返回 -1

示例 1:

输入: s = "leetcode" 输出: 0

示例 2:

输入:s = "loveleetcode" 输出: 2

示例 3:

输入: s = "aabb" 输出: -1

提示:

  • 1 <= s.length <= 105
  • s 只包含小写字母

我的代码

\(T(N) = O(N)\), \(S(N) = O(N)\)

{.line-numbers}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class MySolution387  
{
public int firstUniqChar(String s)
{
if (s==null||s.length()<=0) return -1;
else if (s.length()==1) return 0;

HashMap<Character, Integer> map = new HashMap();
int minIndex = Integer.MAX_VALUE;

for (int i=0; i<s.length(); i++)
{
char ch = s.charAt(i);

if (map.containsKey(ch)&&!(map.get(ch)==-1))
map.replace(ch, -1);

else if (!map.containsKey(ch))
map.put(ch, i);
}

Iterator it = map.keySet().iterator();
for (int i=0; i<map.size(); i++)
{
int index = map.get(it.next());
if (index!=-1&&index<minIndex)
minIndex = index;
}
if (minIndex==Integer.MAX_VALUE) return -1;
else return minIndex;

}
}