letcode - 821 -字符的最短距离 - java版


文章目录

    • 题目
    • 代码

题目 给定一个字符串 S 和一个字符 C。返回一个代表字符串 S 中每个字符到字符串 S 中的字符 C 的最短距离的数组。
示例 1:
输入: S = “loveleetcode”, C = ‘e’
输出: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]
说明:
【letcode - 821 -字符的最短距离 - java版】字符串 S 的长度范围为 [1, 10000]。
C 是一个单字符,且保证是字符串 S 里的字符。
S 和 C 中的所有字母均为小写字母。
代码
/* * @lc app=leetcode.cn id=821 lang=java * * [821] 字符的最短距离 */// @lc code=start class Solution { public int[] shortestToChar(String S, char C) {List list = new ArrayList<>(); for (int i = 0; i < S.length(); i++) { //根据第i个字符把字符串切成两半 //左边的包含此字符,右边的也包含此字符 String left = S.substring(0, i+1); String right = S.substring(i); int lindex=Integer.MAX_VALUE,rindex=Integer.MAX_VALUE; if (left.lastIndexOf(C)!=-1) { lindex=left.length()-1-left.lastIndexOf(C); } if (right.lastIndexOf(C)!=-1) { rindex = right.indexOf(C); } list.add(Math.min(lindex,rindex)); } //转换成数组返回 int[] res = new int[list.size()]; for (int i = 0; i < res.length; i++) { res[i] = list.get(i); } return res; } } // @lc code=end

    推荐阅读