LeetCode821. 字符的最短距离

给定一个字符串 S 和一个字符 C。返回一个代表字符串 S 中每个字符到字符串 S 中的字符 C 的最短距离的数组。

示例 1:

输入: S = "loveleetcode", C = 'e'
输出: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]

说明:

  1. 字符串 S 的长度范围为 [1, 10000]
  2. C 是一个单字符,且保证是字符串 S 里的字符。
  3. S 和 C 中的所有字母均为小写字母。

思路:用链表记录下字符串S中每个字符C的索引位置,遍历字符串S,求得每一个字符距目标字符C的最短距离。

class Solution {
    public int[] shortestToChar(String S, char C) {
         List<Integer> list=new ArrayList<Integer>();//存储S的C的出现索引
	    for(int i=0;i<S.length();i++) {
	    	if(S.charAt(i)==C) {
	    		list.add(i);
	    	}
	    }
	    int result[]=new int[S.length()];
	    for(int i=0;i<S.length();i++) {
	    	if(S.charAt(i)==C) {
	    		result[i]=0;
	    	}else {
	    		int min=Integer.MAX_VALUE;//找到当前字符距相同目标字符的最短距离
	    		for(int t:list) {
	    			int temp=Math.abs(t-i);
	    			if(temp<min) {
	    				min=temp;
	    			}
	    		}
	    		result[i]=min;
	    	}
	    }
		return result;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_40550726/article/details/81276210