Skip to content

Commit cd337a7

Browse files
committed
add uniqueChar code
1 parent d4b4b96 commit cd337a7

File tree

3 files changed

+63
-1
lines changed

3 files changed

+63
-1
lines changed

string/0014-最长公共前缀.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ https://leetcode-cn.com/problems/longest-common-prefix/
1111
输入: ["dog","racecar","car"]
1212
输出: ""
1313
解释: 输入不存在公共前缀。
14-
### 双指针
14+
### 线性比较
1515
* 前两个进行比较,找到公共字符串prefix
1616
* prefix再与后面的比较
1717
```java

string/0387-唯一字符.md

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
## 题目地址
2+
https://leetcode-cn.com/problems/longest-common-prefix/
3+
## 题目描述
4+
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
5+
示例:
6+
s = "leetcode"
7+
返回 0
8+
s = "loveleetcode"
9+
返回 2
10+
### 线性比较
11+
* 遍历每个字符,map中存放key和出现的频率
12+
* map中找到index=1的key返回
13+
```java
14+
public class FindUniqueChar {
15+
public int solution(String s){
16+
HashMap<Character,Integer> map = new HashMap<>();
17+
for (int i=0;i<s.length();i++){
18+
Character c = s.charAt(i);
19+
// build hash map : character and how often it appears
20+
map.put(c,map.getOrDefault(c,0)+1);
21+
}
22+
// find the index
23+
for (int i=0;i<s.length();i++){
24+
Character c = s.charAt(i);
25+
if (map.get(c) ==1){
26+
return i;
27+
}
28+
}
29+
return -1;
30+
}
31+
}
32+
```
33+
#### 复杂度分析
34+
*时间复杂度:O(n)
35+
只遍历了两遍字符串,同时散列表中查找操作是常数时间复杂度的。
36+
*

string/FindUniqueChar.java

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package hash;
2+
//hash相关.q387_字符串中的第一个唯一字符;
3+
//给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1
4+
import java.util.HashMap;
5+
6+
/**
7+
* Hash o(n)
8+
*/
9+
public class FindUniqueChar {
10+
public int solution(String s){
11+
HashMap<Character,Integer> map = new HashMap<>();
12+
for (int i=0;i<s.length();i++){
13+
Character c = s.charAt(i);
14+
// build hash map : character and how often it appears
15+
map.put(c,map.getOrDefault(c,0)+1);
16+
}
17+
// find the index
18+
for (int i=0;i<s.length();i++){
19+
Character c = s.charAt(i);
20+
if (map.get(c) ==1){
21+
return i;
22+
}
23+
}
24+
return -1;
25+
}
26+
}

0 commit comments

Comments
 (0)