Xinqi Bao's Git
1 #include "wordscapes.h"
8 Dictionary::Node::Node() {}
10 Dictionary::Dictionary(const char* filename
)
13 std::ifstream
dictfile(filename
);
15 while (dictfile
>> word
)
20 if (tmp
->next
[ch
- 'a'] == nullptr)
21 tmp
->next
[ch
- 'a'] = new Node();
22 tmp
= tmp
->next
[ch
- 'a'];
29 Dictionary::Node::~Node()
31 for (int i
= 0; i
< 26; i
++)
32 if (next
[i
] != nullptr) delete next
[i
];
35 Dictionary::~Dictionary() { delete header
; }
37 bool Dictionary::findWord(std::string
& word
)
42 if (tmp
->next
[ch
- 'a'] == nullptr) return false;
43 tmp
= tmp
->next
[ch
- 'a'];
48 //TODO: get filename from config file
49 Wordscapes::Wordscapes() { dict
= new Dictionary("myDictionary"); }
51 Wordscapes::~Wordscapes() {}
53 void Wordscapes::stripInput(std::string
& given
, std::string
& search
)
55 for (auto i
= given
.begin(); i
!= given
.end(); i
++)
57 if (*i
>= 'a' && *i
<= 'z')
59 else if (*i
>= 'A' && *i
<= 'Z')
64 for (auto i
= search
.begin(); i
!= search
.end(); i
++)
66 if ((*i
>= 'a' && *i
<= 'z') || *i
== '*')
68 else if (*i
>= 'A' && *i
<= 'Z')
75 std::vector
<std::string
> Wordscapes::solve(std::string
& given
,
78 // strip input string, remove unexpected characters
79 stripInput(given
, search
);
81 std::vector
<std::string
> result
;
82 std::map
<char, int> mp
;
83 std::queue
<std::pair
<std::string
, std::map
<char, int>>> qu
;
85 for (char ch
: given
) mp
[ch
]++;
86 for (char ch
: search
)
88 if (ch
>= 'a' && ch
<= 'z') mp
[ch
]--;
89 if (mp
[ch
] < 0) return {};
91 qu
.push({search
, mp
});
95 std::string word
= qu
.front().first
;
96 auto wmp
= qu
.front().second
;
98 std::size_t found
= word
.find('*');
99 if (found
== std::string::npos
)
101 if (dict
->findWord(word
)) result
.push_back(word
);
109 auto tmp_word
= word
;
111 tmp_word
.replace(found
, 1, 1, m
.first
);
113 qu
.push({tmp_word
, tmp_wmp
});