139. 单词拆分

https://blog.csdn.net/mine_song/article/details/72081998

给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,判定 s 是否可以被空格拆分为一个或多个在字典中出现的单词。

说明:

  • 拆分时可以重复使用字典中的单词。
  • 你可以假设字典中没有重复的单词。
  • class Solution {
        public boolean wordBreak(String s, List<String> wordDict) {
            if(s==null){
                return true;
            }
            if(wordDict==null){
                return false;
            }
             int len=s.length();
            boolean[] dp=new boolean[len+1];//表示dp[i]以i-1结尾是否存在字典中的
           dp[0]=true;
            for(int i=0;i<=len;i++){//substring左闭右开等于也无妨
                for(int j=0;j<i;j++){
                    if(dp[j]&&wordDict.contains(s.substring(j,i))){
                        dp[i]=true;
                        break;
                    }
                }
            }
            return dp[len];
        }
    }

    BFS

  • public boolean wordBreak(String s, List<String> dict) {
    	if (dict.contains(s))
    		return true;
    	Queue<Integer> queue = new LinkedList<Integer>();
    	queue.offer(0);
    	//使用set去检查去除重复计算
    	//这是是时间复杂度降到O(N^2)的关键
    	Set<Integer> visited = new HashSet<Integer>();
    	visited.add(0);
    	while (!queue.isEmpty()) {
    		int curIdx = queue.poll();
    		for (int i = curIdx + 1; i <= s.length(); i++) {
    			if (visited.contains(i))
    				continue;
    			if (dict.contains(s.substring(curIdx, i))) {
    				//如果到达中重点,
    				//注意此时的i是curIdx + 1
    				if (i == s.length())
    					return true;
    				queue.offer(i);
    				visited.add(i);
    			}
    		}
    	}
    	return false;
    }
    

     

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值