Leetcode每日一题:140.word-break-ii(单词拆分)_leetcode
Leetcode每日一题:140.word-break-ii(单词拆分)_leetcode_02
很疑惑,明明代码测试样例输出没问题,提交后的样例点在本地上测试也没问题,但就是通过不了;
Leetcode每日一题:140.word-break-ii(单词拆分)_字符串_03
Leetcode每日一题:140.word-break-ii(单词拆分)_哈希表_04
在本地vscode上明明能得到正确结果;
思路就是DFS+回溯+哈希;

#include <iostream>
#include <vector>
using namespace std;

long hashWord(string s)//对字符串s进行哈希
{
    long val = 0;
    int len = s.size();
    for (int i = 0; i < len; i++)
    {
        val = val * 26 + s[i] - 'a';
    }
    return val;
}

bool find(vector<long> &word, int hashVal)//判断某个字符串的哈希值hashVal是否在单词哈希值列表中,即这个字符串是否为单词
{
    int len = word.size();
    for (int i = 0; i < len; i++)
    {
        if (word[i] == hashVal)
        {
            return true;
        }
    }
    return false;
}

void dfs(string &s, int len, int nowP, int &max, int &min, vector<long> &word, string ss, vector<string> &res)
{
    long hashVal = 0;
    int count = 0;
    int endP = nowP;
    if (endP == len)//边界条件
    {
        ss.pop_back();
        res.push_back(ss);
        return;
    }
    while (endP < len)
    {
        hashVal = hashVal * 26 + s[endP] - 'a';
        count++;
        if (count < min)
        {
            endP++;
            continue;
        }
        if (count > max)//字符串长度超过单词最大长度,不可能为单词,直接return
        {
            return;
        }
        if (find(word, hashVal))
        {
            string temp =ss+ s.substr(nowP, endP - nowP + 1);
            temp.push_back(' ');
            dfs(s, len, endP + 1, max, min, word, temp, res);
        }
        endP++;
    }
}

vector<string> wordBreak(string s, vector<string> &wordDict)
{
    int len1 = s.size();
    int len2 = wordDict.size();
    vector<long> word(len2, 0);
    //hash每个单词并记录最大/小单词长度
    int max = -1, min = INT32_MAX;
    for (int i = 0; i < len2; i++)
    {
        int temp = wordDict[i].size();
        if (temp > max)
        {
            max = temp;
        }
        if (temp < min)
        {
            min = temp;
        }
        word[i] = hashWord(wordDict[i]);
    }
    vector<string> res;
    dfs(s, len1, 0, max, min, word, "", res);
    return res;
}

int main()
{
    vector<string> test;
    test.push_back("apple");
    test.push_back("pen");
    test.push_back("applepen");
    test.push_back("pine");
    test.push_back("pineapple");
    string s = "pineapplepenapple";
    test = wordBreak(s, test);
    for (string s : test)
    {
        cout << s << endl;
    }
    return 0;
}