LeetCode 821 Shortest Distance to a Character

LeetCode 821 Shortest Distance to a Character

portal

topic analysis

Given a string 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:

  1. Sstring length is in[1, 10000].
  2. C is a single character, and guaranteed to be in string S.
  3. All letters in S and C are lowercase.

Personally, it is relatively easy to understand. Given a string and characters, find the minimum distance between the characters in each position and the given string.

think

The number is not too large, I choose to solve it by violence, the idea is simple and easy to understand, search from left to right from the character position, stop the search when a given character is encountered, calculate the distance between the two subscripts, time complexity O ( n 2 )

Code

class Solution {
public:
    vector<int> shortestToChar(string S, char C) {
        int len = S.length();
        // 选取一个比较大的数字
        vector<int> result(len, 30000);
        // 开始暴力
        for (int i = 0; i < len; ++i) {
            for (int j = i; j < len; ++j) {
                // 搜索到字符就可以停止访问
                if (S[j] == C) {
                    result[i] = min(j - i, result[i]);
                    break;
                }
            }

            for (int j = i; j >= 0; --j) {
                // 同等思想
                if (S[j] == C) {
                    result[i] = min(i - j, result[i]);
                    break;
                }
            }
        }
        return result;
    }
};

thoughts

It is also acceptable to use violence to solve the data directly if it is estimated that it is not too large. In fact, if you want to improve this question, you can consider using an auxiliary array to record all the subscripts of a given character. The specific ideas are not rough, and more practice is needed.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324775405&siteId=291194637