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()];
}
}