|
1 | 1 | ### 思路 |
2 | 2 | Array遍历 |
3 | 3 |
|
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 | +``` |
16 | 10 |
|
| 11 | +- 心得 |
| 12 | +``` |
| 13 | +- array的题肯定不会只考array,因为是基础; |
| 14 | +- array一般肯定要考遍历,就像是binary tree;遍历就是左到右,右到左,左右各扫一遍,这是最基本的,可能再有结合双指针/滑动窗口的;总之就是一些结合题目已知条件需要找到合适的便利方式; |
| 15 | +- 这题还可以用stack,边push边更新; |
| 16 | +``` |
17 | 17 |
|
18 | 18 | ### 代码 |
19 | 19 | ```java |
20 | 20 | //array遍历 |
21 | 21 | class Solution { |
22 | 22 | public int[] shortestToChar(String s, char c) { |
23 | | - int pre = Integer.MIN_VALUE / 2; |
24 | 23 | int[] res = new int[s.length()]; |
| 24 | + int ci = 20000; |
| 25 | + Arrays.fill(res, 20000); |
25 | 26 | 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++; |
28 | 32 | } |
29 | 33 |
|
30 | | - pre = Integer.MAX_VALUE; |
31 | 34 | 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++){ |
47 | 35 | 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; |
63 | 37 | } |
| 38 | + res[i] = Math.min(ci, res[i]); |
| 39 | + ci++; |
64 | 40 | } |
65 | 41 |
|
66 | 42 | return res; |
| 43 | + |
67 | 44 | } |
68 | 45 | } |
| 46 | + |
69 | 47 | ``` |
70 | 48 |
|
71 | 49 | ### 复杂度 |
72 | 50 |
|
73 | 51 | Array遍历 |
74 | 52 | O(s.length()); |
75 | 53 | O(1) |
76 | | - |
77 | | -Stack |
78 | | -O(s.length()) |
79 | | -O(N),维护一个栈。 |
0 commit comments