File tree 2 files changed +30
-7
lines changed
387.First Unique Character in a String
2 files changed +30
-7
lines changed Original file line number Diff line number Diff line change 42
42
### 解法
43
43
遍历 string,遇到左括号,压入栈中;遇到右括号,从栈中弹出元素,元素不存在或者元素与该右括号不匹配,返回 false。遍历结束,栈为空则返回 true,否则返回 false。
44
44
45
- 因为字符串只包含"(){}[ ] ",也可以进行特殊处理,用映射来做
45
+ 因为字符串只包含"(){}[ ] ",也可以进行特殊处理,用映射来做。
46
46
47
- #### java
48
- ```
47
+ #### Java 版实现
48
+ ``` java
49
49
class Solution {
50
50
public boolean isValid (String s ) {
51
51
if (s == null || s == " " ) {
@@ -85,8 +85,8 @@ class Solution {
85
85
}
86
86
```
87
87
88
- #### C++
89
- ```
88
+ #### C++ 版实现
89
+ ``` cpp
90
90
91
91
class Solution {
92
92
public:
@@ -135,7 +135,7 @@ public:
135
135
}
136
136
};
137
137
138
- //特殊
138
+ // 特殊
139
139
class Solution {
140
140
public:
141
141
bool isValid(string s) {
@@ -165,4 +165,4 @@ public:
165
165
}
166
166
};
167
167
168
- ```
168
+ ```
Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public:
3
+ int firstUniqChar (string s) {
4
+ vector<int > cnts (26 , 0 ), pos (26 , s.size ()) ;
5
+
6
+
7
+ for (int i = s.size ()-1 ; i >= 0 ; --i)
8
+ {
9
+ int index = s[i] - ' a' ;
10
+ cnts[index ]++ ;
11
+ pos[index ] = i ;
12
+ }
13
+
14
+ int p = s.size () ;
15
+ for (int i = 0 ; i < 26 ; ++i)
16
+ {
17
+ if (cnts[i] == 1 && pos[i] < p)
18
+ p = pos[i] ;
19
+ }
20
+
21
+ return p != s.size ()? p: -1 ;
22
+ }
23
+ };
You can’t perform that action at this time.
0 commit comments