Skip to content

Commit 64bc96b

Browse files
solves shortest distance to word
1 parent cefc669 commit 64bc96b

File tree

2 files changed

+17
-1
lines changed

2 files changed

+17
-1
lines changed

Diff for: README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -221,7 +221,7 @@
221221
| 811 | [Subdomain Visit Count](https://leetcode.com/problems/subdomain-visit-count) | |
222222
| 812 | [Largest Triangle Area](https://leetcode.com/problems/largest-triangle-area) | [![Java](assets/java.png)](src/LargestTriangleArea.java) |
223223
| 819 | [Most Common Word](https://leetcode.com/problems/most-common-word) | [![Java](assets/java.png)](src/MostCommonWord.java) |
224-
| 821 | [Shortest Distance to Character](https://leetcode.com/problems/shortest-distance-to-a-character) | |
224+
| 821 | [Shortest Distance to Character](https://leetcode.com/problems/shortest-distance-to-a-character) | [![Java](assets/java.png)](src/ShortestDistanceToACharacter.java) |
225225
| 824 | [Goat Latin](https://leetcode.com/problems/goat-latin) | |
226226
| 830 | [Positions of Large Groups](https://leetcode.com/problems/positions-of-large-groups) | |
227227
| 832 | [Flipping an Image](https://leetcode.com/problems/flipping-an-image) | |

Diff for: src/ShortestDistanceToACharacter.java

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
public class ShortestDistanceToACharacter {
2+
public int[] shortestToChar(String string, char c) {
3+
int[] answer = new int[string.length()];
4+
for (int i = 0, l = Integer.MIN_VALUE ; i < string.length() ; i++) {
5+
if (string.charAt(i) == c) l = i;
6+
answer[i] = l == Integer.MIN_VALUE ? Integer.MAX_VALUE : i - l;
7+
}
8+
9+
for (int i = string.length() - 1, r = Integer.MAX_VALUE ; i >= 0 ; i--) {
10+
if (string.charAt(i) == c) r = i;
11+
answer[i] = Math.min(answer[i], r - i);
12+
}
13+
14+
return answer;
15+
}
16+
}

0 commit comments

Comments
 (0)