单词拆分 III-LintCode

204 篇文章 0 订阅

给出一个单词表和一条去掉所有空格的句子,根据给出的单词表添加空格, 返回可以构成的句子的数量, 保证构成的句子中所有的单词都可以在单词表中找到.

样例:
给一个字符串 CatMat, 给出字典 [“Cat”, “Mat”, “Ca”, “tM”, “at”, “C”, “Dog”, “og”, “Do”], 返回 3
我们可以构成一下 3 条语句: CatMat = Cat Mat CatMat = Ca tM at CatMat = C at Mat

思路:
回溯法

#ifndef C683_H
#define C683_H
#include<iostream>
#include<unordered_set>
#include<string>
using namespace std;
class Solution {
public:
    /*
    * @param : A string
    * @param : A set of word
    * @return: the number of possible sentences.
    */
    int wordBreak3(string& s, unordered_set<string>& dict) {
        // Write your code here
        if (s.empty() || dict.empty())
            return 0;
        int num = 0;
        helper(s, dict, 0, num);
        return num;
    }
    //pos表示字符串的当前位置,num表示可以组成语句的个数
    void helper(string &s, unordered_set<string>& dict, int pos,int &num)
    {
        if (pos == s.size())//已经遍历玩字符串,num++
        {
            num++;
            return;
        }
        string str;
        //从当前位置向后取字符串,若存在于set中,改变pos的值,深度搜索
        for (int j = 1; j <= s.size() - pos; ++j)
        {
            str = s.substr(pos, j);
            if (dict.find(str) != dict.end())
            {
                helper(s, dict, pos + j, num);
            }
        }
    }
};
#endif
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值