問題
GPT-style tokenizers use Byte Pair Encoding: start from single characters and repeatedly merge the most common pair of neighbors into a new symbol.
- Split every word in
wordsinto characters. Repeated words count multiple times. - Count every pair of adjacent symbols across all words.
- Pick the most frequent pair. If pairs tie, pick the one that is smallest when you compare (first symbol, second symbol) as strings.
- Replace every occurrence of that pair, left to right, with the merged symbol, and record the merged symbol.
- Repeat
num_mergestimes, or stop early when no word has two symbols left.
Implement bpe_merges(words, num_merges).
Input
words: The training words (lowercase letters).
num_merges: How many merges to learn.
Output
Return the merged symbols in the order they were learned.
制約
1 ≤ number of words ≤ 1,000, 1 ≤ length of each word ≤ 30
0 ≤ num_merges ≤ 200
例
入力:
words = ["low", "lower", "lowest"]
num_merges = 2
期待される出力:
expected = ["lo", "low"]
入力:
std::vector<std::string> words = {"low", "lower", "lowest"};
long long num_merges = 2;
期待される出力:
std::vector<std::string> expected = {"lo", "low"};
入力:
string[] words = new string[] {"low", "lower", "lowest"};
long num_merges = 2;
期待される出力:
string[] expected = new string[] {"lo", "low"};
解説
Pairs: "l o" and "o w" appear 3 times each; the tie goes to "l o" ("l" < "o"), giving "lo". Now "lo w" appears 3 times, giving "low". Result: ["lo", "low"].
入力:
words = ["aaa"]
num_merges = 3
期待される出力:
expected = ["aa", "aaa"]
入力:
std::vector<std::string> words = {"aaa"};
long long num_merges = 3;
期待される出力:
std::vector<std::string> expected = {"aa", "aaa"};
入力:
string[] words = new string[] {"aaa"};
long num_merges = 3;
期待される出力:
string[] expected = new string[] {"aa", "aaa"};
解説
"aaa" has the pair "a a" twice. Merging left to right gives "aa" + "a". Then "aa a" merges into "aaa", and the word is a single symbol, so the third merge has nothing to do. Result: ["aa", "aaa"].
参考資料
この課題はCodeUtility用に調整されています。上記の説明と制約に従ってください。