字节条跳动夏令营笔试题 Leetcode 139单词拆分O(n^3)(如何通过字符串哈希,减少时间复杂度,之后改进----O(n^2))

地址

https://leetcode-cn.com/problems/word-break/

描述

在这里插入图片描述

思想

在这里插入图片描述

可以借助字符串哈希的方式,减少时间复杂度,这个之后有时间再研究吧。

代码

class Solution {
    
    
public:
    bool wordBreak(string s, vector<string>& wordDict) {
    
    
        int n=s.length();
        vector<bool> f(n+1,false);
        //将wordDict中出现的字符串加入set中
        //这种unordered_set的初始化学一下
        unordered_set<string> hash(wordDict.begin(),wordDict.end());
        f[0]=true;
        for(int i=1;i<=n;i++){
    
    
            for(int j=0;j<i;j++){
    
    
                //f[j]==true且[j,i]字符串在hash中出现过
                //这部分还可以改进
                if(f[j] &&  hash.find(s.substr(j,i-j))!=hash.end()){
    
    
                    f[i]=true;
                    break;
                }
            }
        }
        return f[n];
    }
};

猜你喜欢

转载自blog.csdn.net/qq_52934831/article/details/121793335