zoukankan      html  css  js  c++  java
  • Java实现 LeetCode 821 字符的最短距离(暴力)

    821. 字符的最短距离

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

    示例 1:

    输入: S = “loveleetcode”, C = ‘e’
    输出: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]
    说明:

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

    class Solution {
         public int[] shortestToChar(String s, char c) {
            int len = s.length();
            int[] arr = new int[len];
            int lastIdx = -1, nextIdx = s.indexOf(c);
    
            for(int i=0; i<len; i++){
                if(nextIdx > -1 && i > nextIdx){
                    lastIdx = nextIdx;
                    nextIdx = s.indexOf(c, i);
                }
    
                if(nextIdx > -1 && lastIdx > -1){
                    arr[i] = Math.min(i-lastIdx, nextIdx-i);
                } else if(lastIdx == -1){
                    arr[i] = nextIdx-i;
                } else if(nextIdx == -1){
                    arr[i] = i-lastIdx;
                }
            }
    
            return arr;
        }
    
    }
    
  • 相关阅读:
    yii框架_用户登录
    判断变量是否定义
    ajax小结
    yii框架_1
    yii框架_1_简单模型搭建与应用
    Greedy Gift Givers
    C# 音量控制 静音 等
    Fidelity Job Opportunities
    SPSiteDataQuery
    eBooks on html javascript & css
  • 原文地址:https://www.cnblogs.com/a1439775520/p/13074476.html
Copyright © 2011-2022 走看看