821. Shortest Distance to a Character
Given a string
Example 1:
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 stringS
.- All letters in
S
andC
are lowercase.
给定字符串S和字符C,返回一个整数数组,表示字符串中字符C的最短距离。
public class ShortestDistanceToACharacter { public int[] shortestToChar(String S, char C) { int[] res = new int[S.length()]; List<Integer> tempList = new ArrayList<>(); for (int i = 0; i < S.toCharArray().length; i++) { if (S.toCharArray()[i] == C) { tempList.add(i); } } for (int i = 0; i < S.toCharArray().length; i++) { int min = S.length(); for (int j = 0; j < tempList.size(); j++) { min = Math.min(Math.abs(tempList.get(j) - i), min); } res[i] = min; } return res; } public static void main(String[] args) { ShortestDistanceToACharacter shortestDistanceToACharacter = new ShortestDistanceToACharacter(); shortestDistanceToACharacter.shortestToChar("loveleetcode", "e".toCharArray()[0]); } }
用的方法很蠢啊。。。学习一下其他方法