단어 목록과 word1 및 word2라는 또 다른 두 단어가 있다고 가정하면 목록에서 이 두 단어 사이의 최단 거리를 찾아야 합니다. 여기서 word1과 word2는 같을 수 있으며 목록에서 두 개의 개별 단어를 나타냅니다. 단어 =["연습", "만드는", "완벽한", "기술", "만드는"]이라고 가정해 봅시다.
따라서 입력이 word1 ="makes", word2 ="skill"과 같으면 출력은 1이 됩니다.
이 문제를 해결하기 위해 다음 단계를 따릅니다. −
-
ret :=10^9, l1 :=10^9, l2 :=-10^9
-
n :=단어의 크기
-
initialize i :=0의 경우, i
-
word[i]가 word1과 같으면 -
-
l1 :=나는
-
-
word[i]가 word2와 같으면 -
-
word1이 word2와 같으면 -
-
l1 :=l2
-
-
l2 :=나는
-
-
ret :=최소 |l2 - l1| 그리고 다시
-
-
리턴 렛
예시
더 나은 이해를 위해 다음 구현을 살펴보겠습니다. −
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int shortestWordDistance(vector<string<& words, string word1, string word2) {
int ret = 1e9;
int l1 = 1e9;
int l2 = -1e9;
int n = words.size();
for (int i = 0; i < n; i++) {
if (words[i] == word1) {
l1 = i;
}
if (words[i] == word2) {
if (word1 == word2) {
l1 = l2;
}
l2 = i;
}
ret = min(abs(l2 - l1), ret);
}
return ret;
}
};
main(){
Solution ob;
vector<string< v = {"practice", "makes", "perfect", "skill", "makes"};
cout << (ob.shortestWordDistance(v, "makes", "skill"));
} 입력
{"practice", "makes", "perfect", "skill", "makes"},"makes", "skill" 출력
1