面试题 17.13. 恢复空格
class Solution {
public int respace(String[] dictionary, String sentence) {
Set<String> dict = new HashSet<>(Arrays.asList(dictionary));
int n = sentence.length();
int[] dp = new int[n + 1];
for (int i = 1; i <= n; i++) {
dp[i] = dp[i - 1] + 1;
for (int idx = 0; idx < i; idx++) {
if (dict.contains(sentence.substring(idx, i))) {
dp[i] = Math.min(dp[i], dp[idx]);
}
}
}
return dp[n];
}
}
class Solution {
public int respace(String[] dictionary, String sentence) {
// 构建字典树
Trie trie = new Trie();
for (String word: dictionary) {
trie.insert(word);
}
// 状态转移,dp[i] 表示字符串的前 i 个字符的最少未匹配数
int n = sentence.length();
int[] dp = new int[n + 1];
for (int i = 1; i <= n; i++) {
dp[i] = dp[i - 1] + 1;
for (int idx: trie.search(sentence, i - 1)) {
dp[i] = Math.min(dp[i], dp[idx]);
}
}
return dp[n];
}
}
class Trie {
TrieNode root;
public Trie() {
root = new TrieNode();
}
// 将单词倒序插入字典树
public void insert(String word) {
TrieNode cur = root;
for (int i = word.length() - 1; i >= 0; i--) {
int c = word.charAt(i) - 'a';
if (cur.children[c] == null) {
cur.children[c] = new TrieNode();
}
cur = cur.children[c];
}
cur.isWord = true;
}
// 找到 sentence 中以 endPos 为结尾的单词,返回这些单词的开头下标。
public List<Integer> search(String sentence, int endPos) {
List<Integer> indices = new ArrayList<>();
TrieNode cur = root;
for (int i = endPos; i >= 0; i--) {
int c = sentence.charAt(i) - 'a';
if (cur.children[c] == null) {
break;
}
cur = cur.children[c];
if (cur.isWord) {
indices.add(i);
}
}
return indices;
}
}
class TrieNode {
boolean isWord;
TrieNode[] children = new TrieNode[26];
public TrieNode() {}
}
116. 填充每个节点的下一个右侧节点指针
class Solution {
public Node connect(Node root) {
if(root == null || root.left == null){
return root;
}
root.left.next = root.right;
if(root.next != null){
root.right.next = root.next.left;
}
connect(root.left);
connect(root.right);
return root;
}
}
class Solution {
public Node connect(Node root) {
dfs(root, null);
return root;
}
private void dfs(Node node, Node next) {
if(node != null) {
node.next = next;
dfs(node.left, node.right);
dfs(node.right, node.next != null ? node.next.left : null);
}
}
}
162. 寻找峰值
public class Solution {
public int findPeakElement(int[] nums) {
for (int i = 0; i < nums.length - 1; i++) {
if (nums[i] > nums[i + 1])
return i;
}
return nums.length - 1;
}
}
class Solution {
public int findPeakElement(int[] nums) {
int left = 0,right = nums.length-1;
while(left<right){
int mid = left + (right - left)/2;
if(nums[mid]>nums[mid+1]){
right = mid;
}else {
left = mid + 1;
}
}
return left;
}
}
class Solution {
public int findPeakElement(int[] nums) {
return searchIndex(nums, 0, nums.length - 1);
}
public int searchIndex(int[]nums, int start, int end) {
if(start == end) {
return start;
}
if(end - start == 1) {
return nums[start] >= nums[end] ? start : end;
}
int idx1 = searchIndex(nums, start, (end+start)/2);
int idx2 = searchIndex(nums, (end+start)/2 + 1, end);
return nums[idx1] >= nums[idx2] ? idx1 : idx2;
}
}
你知道的越多,你不知道的越多。