zoukankan      html  css  js  c++  java
  • LeetCode——Word Break

    Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.

    For example, given
    s = "leetcode",
    dict = ["leet", "code"].

    Return true because "leetcode" can be segmented as "leet code".

    原题链接:https://oj.leetcode.com/problems/word-break/

    题目:给定一个字符串和一个单词词典,推断字符串是否能被切分成空格隔开的存在于词典中的单词序列。

    思路:从头開始依次一个字符地向后截取并推断。逻辑应该是对的。測试超时了。

    	public static boolean wordBreak1(String s, Set<String> dict) {
    		if(dict.size() <= 0)
    			return false;
    		int len = s.length();
    		if(len <= 0)
    			return true;
    		boolean flag = false;
    		for(int i=1;i<=len;i++){
    			String tmp = s.substring(0, i);
    			if(dict.contains(tmp)){
    				if(tmp.length() == len)
    					return true;
    			}
    			flag = wordBreak(s.substring(i),dict);
    		}
    		return flag;
    	}

    动态规划。

    	//dp[i] 代表 字符串(j,i)能被分词否
    	public static boolean wordBreak(String s, Set<String> dict) {
    		int length = s.length();
    		boolean[] dp = new boolean[length + 1];
    		dp[0] = true;
    		for (int i = 1; i <= length; i++) {
    			for (int j = 0; j < i; j++) {
    				if (dp[j] && dict.contains(s.substring(j, i))) {
    					dp[i] = true;
    					break;
    				}
    			}
    		}
    		return dp[length];
    	}





  • 相关阅读:
    Using NAT between the vCenter Server system and ESXi/ESX hosts (1010652)
    Zabbix监控windows进程连接数
    CentOS yum [Errno 14] problem making ssl connection CentOs
    httpSecurity
    Nginx
    线程基础知识
    SqlServler
    关于数据库索引
    Https的底层原理
    Synchronized
  • 原文地址:https://www.cnblogs.com/mqxnongmin/p/10948089.html
Copyright © 2011-2022 走看看