资讯专栏INFORMATION COLUMN

[LeetCode] Shortest Distance to a Character

blankyao / 801人阅读

Problem

Given a string S and a character C, return an array of integers representing the shortest distance from the character C in the string.

Example 1:

Input: S = "loveleetcode", C = "e"
Output: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]

Note:

S string length is in [1, 10000].
C is a single character, and guaranteed to be in string S.
All letters in S and C are lowercase.

Solution

</>复制代码

  1. class Solution {
  2. public int[] shortestToChar(String S, char C) {
  3. int len = S.length();
  4. int[] res = new int[len];
  5. if (S == null || S.length() == 0) return res;
  6. Arrays.fill(res, 10000);
  7. int pre = -1;
  8. for (int i = 0; i < len; i++) {
  9. char ch = S.charAt(i);
  10. if (ch == C) {
  11. pre = i;
  12. res[i] = 0;
  13. } else {
  14. if (pre != -1) {
  15. res[i] = i-pre;
  16. }
  17. }
  18. }
  19. pre = -1;
  20. for (int i = len-1; i >= 0; i--) {
  21. char ch = S.charAt(i);
  22. if (ch == C) {
  23. pre = i;
  24. } else {
  25. if (pre != -1) {
  26. res[i] = Math.min(res[i], pre-i);
  27. }
  28. }
  29. }
  30. return res;
  31. }
  32. }

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/76813.html

相关文章

  • Leetcode PHP题解--D49 821. Shortest Distance to a Ch

    摘要:返回字符串中每一个字符离给定的字符的最短距离。否则,当当前下标大于上一个出现字符的位置,且存在下一个字符时,距离为两者中最小的那个。最终代码若觉得本文章对你有用,欢迎用爱发电资助。 D49 821. Shortest Distance to a Character 题目链接 821. Shortest Distance to a Character 题目分析 给定一个字符串s和一个字符...

    Shisui 评论0 收藏0
  • [Leetcode] Shortest Word Distance 最短单词间距

    摘要:代码第一次写入就先不比较第一次写入就先不比较哈希表法复杂度时间空间思路因为会多次调用,我们不能每次调用的时候再把这两个单词的下标找出来。我们可以用一个哈希表,在传入字符串数组时,就把每个单词的下标找出存入表中。 Shortest Word Distance Given a list of words and two words word1 and word2, return the ...

    jsliang 评论0 收藏0
  • [LeetCode] 317. Shortest Distance from All Buildin

    Problem You want to build a house on an empty land which reaches all buildings in the shortest amount of distance. You can only move up, down, left and right. You are given a 2D grid of values 0, 1 or...

    wall2flower 评论0 收藏0
  • [LeetCode] 244. Shortest Word Distance II

    Problem Design a class which receives a list of words in the constructor, and implements a method that takes two words word1 and word2 and return the shortest distance between these two words in the l...

    Nekron 评论0 收藏0
  • [LeetCode] 243. Shortest Word Distance

    Problem Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list. Example:Assume that words = [practice, makes, perfect, coding, makes]. In...

    高胜山 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<