단어 목록이 있다고 가정합니다. 이 단어들은 구별됩니다. 주어진 단어 목록에서 연결된 모든 단어를 찾는 알고리즘을 고안해야 합니다. 연결된 단어는 실제로 주어진 배열에서 적어도 두 개의 더 짧은 단어로 완전히 구성된 문자열입니다.
따라서 단어가 ["cow", "cows", "cowsgoatcows", "goat", "goatcowsgoat", "hippopotamuses", "deer", "deercowgoatcow"]와 같으면 출력은 ["cowsgoatcows", "염소염소", "사슴소염소"]
이 문제를 해결하기 위해 다음 단계를 따릅니다. −
- isPresent() 함수를 정의하면 str, head, idx, 배열 dp가 필요합니다.
- idx>=str의 크기이면 -
- 참을 반환
- dp[idx]가 -1과 같지 않으면 -
- dp[idx]를 반환
- 노드 생성 curr :=head
- 예:=거짓
- 초기화 i :=idx의 경우, i
- x :=str[i]
- curr의 자식[x]가 아니면 -
- 루프에서 빠져나오기
- 그렇지 않으면
- curr :=curr의 자식[x]
- curr의 isEnd가 참이면 -
- ok :=ok OR isPresent(str, head, i + 1, dp)
- curr의 자식[x] :=새 노드 생성
- curr :=단어[i]
- curr이 ""와 같으면 -
- 다음 부분은 무시하고 다음 반복으로 건너뜁니다.
- 같은 크기의 curr 배열 dp를 정의하고 -1로 채웁니다.
- isPresent(curr, head, 0, dp) 함수 호출이 0이 아닌 경우 -
- ret 끝에 curr 삽입
- 그렇지 않으면
- insertNode(head, curr) 함수 호출
이해를 돕기 위해 다음 구현을 살펴보겠습니다. −
예
#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
cout << "[";
for(int i = 0; i<v.size(); i++){
cout << v[i] << ", ";
}
cout << "]"<<endl;
}
struct Node{
bool isEnd;
map <char, Node*> child;
Node(){
isEnd = false;
}
};
class Solution {
public:
bool isPresent(string str, Node* head, int idx, vector <int>& dp){
if(idx >= str.size())return true;
if(dp[idx] != -1)return dp[idx];
Node* curr = head;
bool ok = false;
for(int i = idx; i < str.size(); i++){
char x = str[i];
if(!curr->child[x]){
break;
}else{
curr = curr->child[x];
}
if(curr->isEnd){
ok |= isPresent(str, head, i + 1, dp);
}
}
return dp[idx] = ok;
}
static bool cmp(string s1, string s2){
return s1.size() < s2.size();
}
void insertNode(Node* head, string s){
Node* curr = head;
for(int i = 0; i < s.size(); i++){
char x = s[i];
if(!curr->child[x]){
curr->child[x] = new Node();
}
curr = curr->child[x];
}
curr->isEnd = true;
}
vector<string> findAllConcatenatedWordsInADict(vector<string>& words) {
Node* head = new Node();
sort(words.begin(), words.end(), cmp);
vector <string> ret;
for(int i = 0; i < words.size(); i++){
string curr = words[i];
if(curr=="")continue;
vector <int> dp(curr.size(), -1);
if(isPresent(curr, head, 0, dp)){
ret.push_back(curr);
}else{
insertNode(head, curr);
}
}
return ret;
}
};
main(){
Solution ob;
vector<string> v = {"cow","cows","cowsgoatcows","goat","goatcowsgoat","hippopotamuses","deer","deercowgoatcow"};
print_vector(ob.findAllConcatenatedWordsInADict(v));
} 입력
{"cow","cows","cowsgoatcows","goat","goatcowsgoat","hippopotamuses","deer","deercowgoatcow"} 출력
[cowsgoatcows, goatcowsgoat, deercowgoatcow, ]