题目描述
leetcode 139.单词拆分
思路
- 维护一个队列,用指针描述一个节点。
- 起初,指针 0 入列,然后它出列,指针 1,2,3,4,5,6,7,8 是它的子节点,分别与 0 围出的前缀子串(左闭右开的围),是单词就让它入列,继续考察以它(右区间,即儿子)为起点的剩余子串;不是单词,对应的指针不入列
- 然后重复地做:节点(指针)出列,考察它的子节点,能入列的就入列、再出列……
- 直到指针越界,没有剩余子串了,没有指针可入列,如果前缀子串是单词,说明之前一直在切出单词,返回 true。
- 如果整个BFS过程,始终没有返回true,则返回 false。
代码
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
unordered_set<string> us(wordDict.begin(),wordDict.end());
vector<bool> visited(s.length(),false);
queue<int> q;
q.push(0);
while(!q.empty())
{
int start=q.front();
q.pop();
if(visited[start])
continue;
visited[start]=true;
for(int i=start+1;i<=s.length();i++)
{
string str(s.begin()+start,s.begin()+i);
if(us.count(str))
{
if(i<s.length())
q.push(i);
else
return true;
}
}
}
return false;
}
};