class Solution {
public:
string replaceWords(vector<string>& dict, string sentence)
{
unordered_map<string, int> table;
for (int i = 0; i<dict.size(); i++)
{
if (table.find(dict[i]) == table.end())
table[dict[i]] = 1;
} //init the word dict map
int i = 0;
int flag = 0;//是否正在搜素新的words
string words;
string res;
int temp = 0; //当前搜寻的words未匹配成功
while (i<sentence.size())
{
if (flag == 0 && temp == 0)
words.erase();
if (flag == 0) //还未开始搜寻words
{
if (sentence[i] != ' '&&temp == 0)
{
flag = 1;
words = words + sentence[i];
if (table.find(words) != table.end())
{
res = res + words + " ";
temp = 1;
}
}
i++;
}
else //正在搜寻words
{
if (sentence[i] == ' ') //the ends of the word
{
if (temp == 0 && table.find(words) != table.end())
{
res = res + words;
}
if (temp == 0)
res = res + words + ' ';
i++;
flag = 0;
temp = 0;
}
else
{
if (temp == 0)
{
words = words + sentence[i];
if (table.find(words) != table.end())
{
res = res + words + " ";
temp = 1;
}
}
i++;
}
}
}
if (flag = 1&&temp==0)
res += words + " ";
res.erase(res.size()-1);
return res;
}
};
648. Replace Words
最新推荐文章于 2021-09-12 00:10:56 发布