Skip to content

Commit 2676bdc

Browse files
committed
Update array-821-Shortest_Distance_to_a_Character.md
1 parent df8080e commit 2676bdc

1 file changed

Lines changed: 24 additions & 50 deletions

File tree

Lines changed: 24 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -1,79 +1,53 @@
11
### 思路
22
Array遍历
33

4-
两次遍历
5-
- 第一次从左到右,遇到c,将其右边的依次从1-m编号;直到遇到下一个c,重复编号过程。(第一个c左边为未编号状态)
6-
- 第二次从右到左,遇到c,将其左边当前编号与预计编号比较并取min;第二次编号并会将第一个c左边的编号完成。
7-
8-
Stack
9-
将s遍历一次
10-
- 如果当前为c,
11-
- pop站内元素,并依次按距离递增编号;直到栈空或栈顶为c;当前位置编号0;将当前位置压入栈
12-
- 如果当前不为c
13-
- 如果栈顶为c,那么当前位置编号1
14-
- 否则当前位置编号为前一个位置编号+1;
15-
- 将当前位置index 压入栈;
4+
- 思路与解法
5+
```
6+
- 左右两边各扫一遍;
7+
- 第一遍扫出初始编号;
8+
- 第二遍更新编号找最小值;
9+
```
1610

11+
- 心得
12+
```
13+
- array的题肯定不会只考array,因为是基础;
14+
- array一般肯定要考遍历,就像是binary tree;遍历就是左到右,右到左,左右各扫一遍,这是最基本的,可能再有结合双指针/滑动窗口的;总之就是一些结合题目已知条件需要找到合适的便利方式;
15+
- 这题还可以用stack,边push边更新;
16+
```
1717

1818
### 代码
1919
```java
2020
//array遍历
2121
class Solution {
2222
public int[] shortestToChar(String s, char c) {
23-
int pre = Integer.MIN_VALUE / 2;
2423
int[] res = new int[s.length()];
24+
int ci = 20000;
25+
Arrays.fill(res, 20000);
2526
for(int i = 0;i < s.length();i++){
26-
if(s.charAt(i) == c) pre = i;
27-
res[i] = i - pre;
27+
if(s.charAt(i) == c){
28+
ci = 0;
29+
}
30+
res[i] = Math.min(ci, res[i]);
31+
ci++;
2832
}
2933

30-
pre = Integer.MAX_VALUE;
3134
for(int i = s.length() - 1;i >= 0;i--){
32-
if(s.charAt(i) == c) pre = i;
33-
res[i] = Math.min(res[i], pre - i);
34-
}
35-
36-
return res;
37-
}
38-
}
39-
40-
//stack
41-
class Solution {
42-
public int[] shortestToChar(String s, char c) {
43-
Stack<Integer> stack = new Stack<>();
44-
int[] res = new int[s.length()];
45-
stack.add(0);
46-
for(int i = 0;i < s.length();i++){
4735
if(s.charAt(i) == c){
48-
int pos = 0;
49-
while(!stack.isEmpty() && s.charAt(stack.peek()) != c){
50-
int cur = stack.pop();
51-
52-
res[cur] = res[cur] == 0?++pos:Math.min(++pos, res[cur]);
53-
}
54-
res[i] = 0;
55-
stack.add(i);
56-
} else {
57-
if(!stack.isEmpty() && s.charAt(stack.peek()) == c){
58-
res[i] = 1;
59-
} else if(i > 0 && res[i-1] != 0) {
60-
res[i] = res[i-1] + 1;
61-
}
62-
stack.add(i);
36+
ci = 0;
6337
}
38+
res[i] = Math.min(ci, res[i]);
39+
ci++;
6440
}
6541

6642
return res;
43+
6744
}
6845
}
46+
6947
```
7048

7149
### 复杂度
7250

7351
Array遍历
7452
O(s.length());
7553
O(1)
76-
77-
Stack
78-
O(s.length())
79-
O(N),维护一个栈。

0 commit comments

Comments
 (0)