LeetCode经典编程题(四)

linked-list-cycle

Description

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

Solution

Use a fast pointer and a slow pointer. If there is a cycle, they will meet each other.

Code
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public boolean hasCycle(ListNode head) {
        ListNode fast = head, slow = head;
        while(fast!=null && slow!=null && fast.next!=null){
            fast = fast.next.next;
            slow = slow.next;
            if(fast == slow){
                return true;
            }
        }
        return false;
    }
}

2. word-break-ii

Description

Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.

Return all such possible sentences.

For example, given
s =“catsanddog”,
dict =[“cat”, “cats”, “and”, “sand”, “dog”].

A solution is[“cats and dog”, “cat sand dog”].

Solution

reference: https://www.nowcoder.com/questionTerminal/bd73f6b52fdc421d91b14f9c909f9104
Split a string into two part. Result set = left part (correct words in dict) + right part (all possible right part [ use recursive function ]).

Code
import java.util.*;
public class Solution {
    public ArrayList<String> wordBreak(String s, Set<String> dict) {
        Map<String,ArrayList<String>> map = new HashMap<>();
        return dfs(map,s,dict);
    }
    
    private ArrayList<String> dfs(Map<String,ArrayList<String>> map, String s, Set<String> dict){
        if(map.containsKey(s)){
            return (ArrayList<String>)map.get(s);
        }
        ArrayList<String> list = new ArrayList<>();
        if(s.equals("")){
            list.add("");
        }else{
            for(int i = 0; i < s.length(); i++){
                String sub = s.substring(0, i);
                if(dict.contains(sub)){
                    ArrayList<String> leftStr = dfs(map, s.substring(i), dict);
                    if(leftStr.size() == 0){
                        continue;
                    }else{
                        for(int j = 0; j < leftStr.size(); j++){
                            list.add((sub+" "+ leftStr.get(j)).trim());
                        }
                    }
                }
                
            }
        }
        map.put(s, list);
        return list;
    }
    
}

3. word-break

Description

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".

Solution

1、 recursive method : If dict contains s.substring(0, i) and the wordBreak result of s.substring(i) is true, return true.
However, this method turns out timeout.
2、dynamic plan : dp[i] represents whether s[0, i] can be split by dict. dp[0] = true. dp[i] = dp[j] && dict.contains(s.substring(j, i)).

code
import java.util.Set;
public class Solution {
    public boolean wordBreak(String s, Set<String> dict) {
        if(s == null || s.length() == 0 || dict == null){
            return false;
        }
        boolean dp[] = new boolean[s.length() + 1];
        dp[0] = true;
        for (int i = 1; i <= s.length(); i++) {
            for(int j = 0; j < i; j++){
                if(dp[j] && dict.contains(s.substring(j, i))){
                    dp[i] = true;
                    break;
                }
            }
        }
        return dp[s.length()];
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值