본문 바로가기

Algorithm/Implementation

(C++) - LeetCode (easy) 819. Most Common Word

반응형

https://leetcode.com/problems/shortest-distance-to-a-character/description/

 

Shortest Distance to a Character - LeetCode

Can you solve this real interview question? Shortest Distance to a Character - Given a string s and a character c that occurs in s, return an array of integers answer where answer.length == s.length and answer[i] is the distance from index i to the closest

leetcode.com

구현 문제였습니다.

📕 풀이방법

📔 입력 및 초기화

1. 정답 vector 변수 shortest

2. c의 위치 index를 저장할 vector 변수 positions를 선언해줍니다.

3. s에 대해 for loop를 수행하며 c와 같은 문자가 나오면 index를 positions에 넣어줍니다.

📔 풀이과정

2차원 for loop를 수행하며 답을 찾아 shortest에 push_back해줍니다.

1. 먼저 s에 대해 수행하고, positions의 원소에 대해 수행해줍니다.

2. 가장 가까운 position을 minPost에 저장해줍니다.

📔 정답 출력 | 반환

shortest를 반환합니다.


📕 Code

📔 C++

class Solution {
public:
    vector<int> shortestToChar(string s, char c) {
        vector<int> shortest;
        vector<int> positions;

        for(int i = 0; i < s.size(); i++) {
            if(s[i] == c) positions.push_back(i);
        }

        for(int i = 0; i < s.size(); i++) {
            int minPos = 0x3f3f3f3f;
            for(auto p : positions) {
                minPos = min(minPos, abs(i-p));
            }
            shortest.push_back(minPos);
        }
        return shortest;
    }
};

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.