Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 169ed95

Browse files
committed
first-unique-character-in-a-strin
1 parent ea62c37 commit 169ed95

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@ leetcode by rust
66
- 229:求众数 II
77
- [src](https://leetcode-cn.com/problems/majority-element-ii/)
88
- [leetcode](https://leetcode-cn.com/problems/majority-element-ii/)
9+
- 387:字符串中的第一个唯一字符
10+
- [src](https://leetcode-cn.com/problems/first-unique-character-in-a-string/)
11+
- [leetcode](https://leetcode-cn.com/problems/first-unique-character-in-a-string/)
912

1013
- 746:使用最小花费爬楼梯
1114
- [src](https://github.com/rustors/leetcode/blob/main/src/bin/check-if-n-and-its-double-exist.rs)
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
fn main() {}
2+
3+
struct Solution;
4+
5+
impl Solution {
6+
/// 因为都是小写字母,所以最多只有26种字符,
7+
/// 申请一个26位长的数组,循环遍历字符串,每个字符的下标对应位字符-'a',
8+
/// 每次循环,数组中对应下标的值+1;遍历字符串后,再遍历字符串一次,
9+
/// 找到字符对应下标的值,值为1则说明只存在一次。因此对应的下标则为所求。
10+
pub fn first_uniq_char(s: String) -> i32 {
11+
let mut a = [0; 26];
12+
let a_char = 'a' as usize;
13+
14+
for &i in s.as_bytes().iter() {
15+
a[(i as usize) - a_char] += 1;
16+
}
17+
18+
for (i, &value) in s.as_bytes().iter().enumerate() {
19+
if a[(value as usize) - a_char] == 1 {
20+
return i as i32;
21+
}
22+
}
23+
-1
24+
}
25+
}

0 commit comments

Comments
 (0)