当前位置: 代码迷 >> 综合 >> LeetCode-Java-821. Shortest Distance to a Character
  详细解决方案

LeetCode-Java-821. Shortest Distance to a Character

热度:56   发布时间:2023-12-16 09:10:38.0

题目

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 [] result = new int[len];int temp = 10001;for(int i=0;i<len;i++){char t = S.charAt(i);if(t==C){temp = 0;}else{temp++;}result[i] = temp;}temp = 10001;for(int i=len-1;i>=0;i--){char t = S.charAt(i);if(t==C){temp = 0;}else{temp++;}if(result[i]>temp){result[i] = temp;}}return result;}
}
  相关解决方案