The shortest distance algorithm of endless character

Given a string of a character S and C. Returns a string representative of each character in the array S the shortest distance S in the string of characters C.

Example 1:

Input: S = "loveleetcode", C = 'e'
Output: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]
Description:
3
length of the string S [1, 10000].
C is a single character, and to ensure that the characters in the string S.
All the letters S and C are all lowercase letters.

Ideas:

Traversing from left to right again, and then again from right to left traversal

answer:

class Solution {
    public int[] shortestToChar(String S, char C) {
        char[] s = S.toCharArray();
        int[] res = new int[S.length()];
        boolean flag = false;
        int count = 1;
        for(int i=0; i<s.length; i++){
            if(s[i] == C){
                flag = true;
                count = 0;
            }
            if(flag){
                res[i] = res[i] < count && res[i] != 0 ? res[i] : count;
                count ++;
            }
        }
        flag = false;
        for(int i = s.length-1; i >= 0; i--){
            if(s[i] == C){
                count = 0;
                flag = true;
            }
            if(flag){
                res[i] = res[i] < count && res[i] != 0 ? res[i] : count;
                count++;
            }
        }
        return res;
    }
}
He published 188 original articles · won praise 323 · views 30000 +

Guess you like

Origin blog.csdn.net/qq_33709508/article/details/104231243