LeetCode Notebook 2020-2021
  • 序
  • 目录
  • 线性表
    • 数组
      • Remove Duplicates from Sorted Array
      • Remove Duplicates from Sorted Array II
      • Exercises I
      • Search in Rotated Sorted Array
      • Search in Rotated Sorted Array II
      • Median of Two Sorted Arrays
      • Longest Consecutive Sequence
      • Exercises II
      • Two Sum
      • 3Sum
      • 3Sum Closest
      • 4Sum
      • Exercises III
      • Next Permutation
      • Permutation Sequence
      • Exercises IV
      • Valid Sudoku
      • Trapping Rain Water
      • Rotate Image
      • Plus One
      • Exercises V
      • Climbing Stairs
      • Set Matrix Zeroes
      • Gray Code
      • Gas Station
      • Exercises VI
      • Candy
      • Single Number
      • Single Number II
      • Exercises VII
    • 链表
      • Add Two Numbers
      • Reverse Linked List II
      • Partition List
      • Swap-nodes-in-pairs
  • 字符串
    • 字符串
      • Valid Palindrome
      • Implement strStr()
      • String to Integer(atoi)
      • Add Binary
      • Longest Palindromic Substring
      • Longest Common Subsequence
      • Regular Expression Matching
      • Rearrange Spaces Between Words
      • Longest Common Prefix
      • Wildcard Matching
      • subdomain visit count
  • 栈和队列
    • 栈
      • Min Stack
      • Valid Parentheses
    • 队列
  • 树
    • 二叉树的遍历
      • Binary Tree Preorder Traversal
      • Binary Tree Inorder Traversal
      • Binary Tree Postorder Traversal
      • Search in a Binary Search Tree
    • 二叉树的构造
      • Untitled
    • 二叉查找树
      • Validate Binary Search Tree
    • 二叉树的递归
      • Untitled
  • 图
    • 图
  • 排序
    • 排序
      • Merge Sorted Array
      • Merge Two Sorted Lists
      • Merge k Sorted Lists
      • Exercises I
      • Insertion Sort List
      • Sort List
      • Sort Color
      • First Missing Positive
      • Exercises II
  • 查找
    • 查找
      • Random Pick with Weight
      • Prefix and Suffix Search
      • Search Insert Position
      • Search a 2D Matrix
  • BFS
    • BFS
  • DFS
    • DFS
      • Split a String Into the Max Number of Unique Substrings
      • Palindrome Partitioning
      • Unique Path
      • Unique Path II
  • 动态规划
    • DP
      • Coin Change
      • Maximal Rectangle
      • Super Egg Drop
      • Exercises
      • Best Team With No Conflicts
  • 分治法
    • Divide And Conquer
  • 贪心法
    • Greedy
      • Jump Game
      • Jump Game II
      • Best time to buy and sell stock
      • Best time to buy and sell stock II
      • Container with most water
      • Exercises
  • 暴力枚举
    • Brute Force
      • Subsets
      • Subsets II
      • Permutation
      • Permutation II
      • Combinations
      • Letter Combinations of a Phone Number
  • others
    • 小岛题
    • 滑动窗口
      • Longest substring without repeating characters
      • Sliding Window Maximum
      • Max Consecutive One III
      • Count Number of Nice Subarrays
    • Roman number code
    • Untitled
由 GitBook 提供支持
在本页
  • Prefix and Suffix Search
  • 描述
  • 例子
  • 约束条件
  • 解法一(runtime error)
  • 解法二
  • 解法三
  • 总结

这有帮助吗?

  1. 查找
  2. 查找

Prefix and Suffix Search

hard 原题链接:https://leetcode.com/problems/prefix-and-suffix-search/

上一页Random Pick with Weight下一页Search Insert Position

最后更新于4年前

这有帮助吗?

Prefix and Suffix Search

原题链接:

描述

Design a special dictionary which has some words and allows you to search the words in it by a prefix and a suffix.

Implement the WordFilter class:

  • WordFilter(string[] words) Initializes the object with the words in the dictionary.

  • f(string prefix, string suffix) Returns the index of the word in the dictionary which has the prefix prefix and the suffix suffix. If there is more than one valid index, return the largest of them. If there is no such word in the dictionary, return -1.

例子

Input ["WordFilter", "f"] [[["apple"]], ["a", "e"]]

Output [null, 0]

Explanation WordFilter wordFilter = new WordFilter(["apple"]); wordFilter.f("a", "e"); // return 0, because the word at index 0 has prefix = "a" and suffix = 'e".

约束条件

  • 1 <= words.length <= 15000

  • 1 <= words[i].length <= 10

  • 1 <= prefix.length, suffix.length <= 10

  • words[i], prefix and suffix consist of lower-case English letters only.

  • At most 15000 calls will be made to the function f.

解法一(runtime error)

class WordFilter {
public:
    vector <string> s;
    WordFilter(vector<string>& words) {
        s.assign(words.begin(), words.end());
    }
    
    int f(string prefix, string suffix) {
        for(int i=0; i<s.size(); i++){
            if(s[i].compare(0, prefix.size()-1, prefix)&&s[i].compare(s[i].size()-suffix.size()-1, suffix.size()-1, suffix)) return i;
    }
        return -1;
    }
};

["WordFilter","f","f","f","f","f","f","f","f","f","f"] [[["cabaabaaaa","ccbcababac","bacaabccba","bcbbcbacaa","abcaccbcaa","accabaccaa","cabcbbbcca","ababccabcb","caccbbcbab","bccbacbcba"]],["bccbacbcba","a"],["ab","abcaccbcaa"],["a","aa"],["cabaaba","abaaaa"],["cacc","accbbcbab"],["ccbcab","bac"],["bac","cba"],["ac","accabaccaa"],["bcbb","aa"],["ccbca","cbcababac"]]

解法二

class WordFilter {
    public:
    unordered_map<string, int> map;
    WordFilter(vector<string>& words) {
        for(int w = words.size()-1; w >=0; w--){
            for(int i = 0; i <= 10 && i<= words[w].size(); i++){
                for(int j = 0; j <= 10 && j <= words[w].size(); j++){
                    map.insert(std::pair<string,int>(words[w].substr(0,i)+"#"+ words[w].substr(words[w].size()-j), w));
                }
            }
        }
    }
    int f(string prefix, string suffix) {
        return (map.count(prefix + "#" + suffix))? map.find(prefix + "#" + suffix)->second : -1;
    }
};

解法三

class TrieNode{
public:
    vector<TrieNode*> next;
    vector<int> idx_list;
    TrieNode(){
        next = vector<TrieNode*> (26, NULL);
    }
};

class Trie{
public:
    TrieNode* root;
    Trie(){
        root = new TrieNode();
    }
    void insert(string word, int idx){
        root->idx_list.push_back(idx); // Deal with empty string case
        TrieNode* cur = root;
        for(int i = 0; i < word.size(); i++){
            if(!cur->next[word[i] - 'a'])
                cur->next[word[i] - 'a'] = new TrieNode();
            cur = cur->next[word[i] - 'a'];
            cur->idx_list.push_back(idx);
        }
    }
    vector<int> find(string word){
        TrieNode* cur = root;
        for(int i = 0; i < word.size(); i++){
            cur = cur->next[word[i] - 'a'];
            if(!cur) return {};
        }
        return cur->idx_list;
    }
};

class WordFilter {
public:
    Trie* forward;
    Trie* backward;
    WordFilter(vector<string> words) {
        forward = new Trie();
        backward = new Trie();
        for(int i = 0; i < words.size(); i++){
            forward->insert(words[i], i);
            string rword = words[i];
            reverse(rword.begin(), rword.end());
            backward->insert(rword, i);
        }
    }
    
    int f(string prefix, string suffix) {
        vector<int> pre = forward->find(prefix);
        reverse(suffix.begin(), suffix.end());
        vector<int> post = backward->find(suffix);
        int i = pre.size() - 1;
        int j = post.size() - 1;
        while(i >= 0 && j >= 0){
            if(pre[i] == post[j]) return pre[i];
            else if(pre[i] > post[j]) i--;
            else j--;
        }
        return -1;
    }
};

总结

使用:

https://leetcode.com/problems/prefix-and-suffix-search/
Hashmap
Trie方法