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.
class Solution { public int[] shortestToChar(String S, char C) { int len = S.length(); int[] res = new int[len]; if (S == null || S.length() == 0) return res; Arrays.fill(res, 10000); int pre = -1; for (int i = 0; i < len; i++) { char ch = S.charAt(i); if (ch == C) { pre = i; res[i] = 0; } else { if (pre != -1) { res[i] = i-pre; } } } pre = -1; for (int i = len-1; i >= 0; i--) { char ch = S.charAt(i); if (ch == C) { pre = i; } else { if (pre != -1) { res[i] = Math.min(res[i], pre-i); } } } return res; } }
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/76813.html
摘要:返回字符串中每一個字符離給定的字符的最短距離。否則,當當前下標大于上一個出現字符的位置,且存在下一個字符時,距離為兩者中最小的那個。最終代碼若覺得本文章對你有用,歡迎用愛發電資助。 D49 821. Shortest Distance to a Character 題目鏈接 821. Shortest Distance to a Character 題目分析 給定一個字符串s和一個字符...
摘要:代碼第一次寫入就先不比較第一次寫入就先不比較哈希表法復雜度時間空間思路因為會多次調用,我們不能每次調用的時候再把這兩個單詞的下標找出來。我們可以用一個哈希表,在傳入字符串數組時,就把每個單詞的下標找出存入表中。 Shortest Word Distance Given a list of words and two words word1 and word2, return the ...
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...
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...
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...
閱讀 3482·2021-09-06 15:13
閱讀 1531·2021-09-02 10:19
閱讀 2477·2019-08-30 15:52
閱讀 924·2019-08-29 15:25
閱讀 1570·2019-08-26 18:36
閱讀 499·2019-08-26 13:23
閱讀 1337·2019-08-26 10:46
閱讀 3505·2019-08-26 10:41