Get all palidromes after delete - Linkedin


给一个string, 可以删除任意字符,求所有可以得到的palidrome字串集
http://www.mitbbs.com/article_t/JobHunting/33053715.html
private static ISet<string> getPal(string s){
  IDictionary<char, IList<int>> dict = new Dictionary<char, IList<int>>();
  for(int i = 0; i < s.Length; i++){
    if(!dict.ContainsKey(s[i])) dict[s[i]] = new List<int>();
    dict[s[i]].Add(i);
  }
  ISet<string> result = new HashSet<string>();
  dfs(result, new StringBuilder(), new StringBuilder(), s, 0, s.Length - 1, 
dict);
  return result;
}
private static void dfs(ISet<string> result, StringBuilder sLeft, 
StringBuilder sRight, string s, int left, int right, IDictionary<char, IList
<int>> dict){
  for(int i = left; i <= right; i++){
    result.Add(sLeft.ToString() + s[i] + sRight.ToString());
    for(int j = 0; j < dict[s[i]].Count; j++)
      if(dict[s[i]][j] <= i) continue;
      else if (dict[s[i]][j] > right) break;
      else{
        sLeft.Append(s[i]);
        sRight.Insert(0, s[i]);
        result.Add(sLeft.ToString() + sRight.ToString());
        dfs(result, sLeft, sRight, s, i + 1, dict[s[i]][j] - 1, dict);
        sLeft.Length -= 1;
        sRight.Remove(0, 1);
        dfs(result, sLeft, sRight, s, i + 1, dict[s[i]][j] - 1, dict);
      }
  }
}

function reverse(s) {
    var o = '';
    for (var i = s.length - 1; i >= 0; i--)
        o += s[i];
    return o;
};

var p = function(s) {
    var prevLookup = {};
    var nextLookup = {};
    
    for (var i = 0; i < s.length; i++) {
        var c = s.charAt(i);
        if (!prevLookup[c]) {
            prevLookup[c] = [];
            nextLookup[c] = [];
        }
    }

    for (var i = 0; i < s.length; i++) {
        for(var c in prevLookup) {
            var lookup = prevLookup[c];
            if (c == s.charAt(i)) {
                lookup[i] = i;
            } else {
                if (i == 0) {
                    lookup[i] = null;
                } else {
                    lookup[i] = lookup[i-1];
                }
            }
        }
    }

    for (var i = s.length-1; i >= 0; i--) {
        for(var c in nextLookup) {
            var lookup = nextLookup[c];
            if (c == s.charAt(i)) {
                lookup[i] = i;
            } else {
                if (i == s.length-1) {
                    lookup[i] = null;
                } else {
                    lookup[i] = lookup[i+1];
                }
            }
        }
    }

    console.log(prevLookup);
    console.log(nextLookup);

    var _rec = function(left, right, accum) {
        console.log(accum + reverse(accum));
        if (left > right) return;


        for (var c in prevLookup) {
            var leftMostPos = nextLookup[c][left];
            var rightMostPos = prevLookup[c][right];
            if (leftMostPos != null && leftMostPos <= right) {
                console.log(accum + c + reverse(accum));
                if (rightMostPos > leftMostPos) {
                    _rec(leftMostPos + 1, rightMostPos -1, accum + c);
                }
            }
        }
    };

    _rec(0, s.length-1, "");
};

var s = "abcbabcba";
var s2 = "aaaaaaaa";
无重复的逐一完全遍历所有的substring 
palindrome。复杂度就是O(the number of palindrome substrings).
blaze 的解法很巧妙。关键是建立两个不同方向的lookup table,每个entry分别是字符
以及一个数组,数组中的 i 元素 是从 i 位置往左(右)看能看到的该字符的最近位
置。然后从两边向中间扫描。

关于leetcode 266, 267 参考:

http://buttercola.blogspot.com/2015/08/leetcode-palindrome-perm
very nice solution
关键是对每个可能的char,维护了一维数组,数组中的i意思是从这个i看过去下一个
same char出现的位置,这样DFS就是对char来做遍历。
而且这个解法很巧妙的解决了奇数长和偶数长的问题。
我的java实现,参考了Blaze的思路,不过不知道真正理解了他的思路没有,因为我不
太看得懂javascript.下面是几个点:

1. 这个题目用的是backtracking而不是dp,因为dp不可能给你产生排列组合。dp通常
就是给你一个最值。
2. 时间复杂度是指数级。
3. 题目的本质是产生排列。
4. 一般的backtracking来形成字符串的话,从现有字母集中每次任意挑一个字母,然后
从剩下的字母里继续挑。把所有字母都加到字符串里面去了,这轮程序也就完了。这个
题目因为有个顺序的限制条件,决定程序怎样进行下去并不能用剩下多少字符来决定,
而应该是用已经加入字符串的字母的位置来决定。


import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Set;

public class Example5 {
    public static void main(String [] args){
        Example5 o = new Example5();
        List <String> results = o.setUp("abcbabcba");
        for(String str: results){
            System.out.println(str);
        }
    }
    public List <String> setUp(String palidrome){
        HashMap <Character, List<Integer>> map = new HashMap <Character, 
List<Integer>>();
        HashMap <Character, Pointers> locations = new HashMap <Character, 
Pointers>();
        char [] chs = palidrome.toCharArray();
        int i = 0;
        for(i=0;i<chs.length;i++){
            if(map.containsKey(chs[i])){
                map.get(chs[i]).add(i);
            }
            else{
                List <Integer> tmp = new ArrayList <Integer> ();
                tmp.add(i);
                map.put(chs[i],tmp);
            }
        }
        Set <Character> keySet = map.keySet();
        Iterator <Character> iter = keySet.iterator();
        List <String > results = new ArrayList <String> ();
        while(iter.hasNext()){
            Character ch=iter.next();
            //results.add(ch.toString());
            int size = map.get(ch).size();
            locations.put(ch, new Pointers(0,size-1));
        }
        StringBuilder sb1 = new StringBuilder();
        StringBuilder sb2 = new StringBuilder();
        dfs(results,0,chs.length-1,sb1,sb2,keySet,map,locations);
        return results;                    
    }
    
    private class Pointers {
        int left;
        int right;
        public Pointers(int left, int right){
            this.left = left;
            this.right = right;
        }
    }
    
    public void dfs (List <String> results, int left, int right, 
StringBuilder sb1, StringBuilder sb2, Set <Character> keySet, HashMap <
Character, List<Integer>> map, HashMap <Character, Pointers> locations) {
        Iterator <Character> iter = keySet.iterator();
        while(iter.hasNext()){
            Character ch=iter.next();
            //System.out.println("ch="+ch+" left="+left+" right="+right);
            Pointers p=locations.get(ch);
            //System.out.println("left1="+p.left+" right1="+p.right);
            List <Integer> nums = map.get(ch);
            int oldLeft = p.left;
            int oldRight = p.right;
            while((p.left<=p.right)&&(nums.get(p.left)<left)){
                p.left++;
            }
            while((p.left<=p.right)&&(nums.get(p.right)>right)){
                p.right--;
            }
            if(p.left<=p.right){
                results.add(sb1.toString()+ch+sb2.toString());
                //System.out.println(sb1.toString()+ch+sb2.toString());
            }
            if(p.left<p.right){
                sb1.append(ch);
                sb2.insert(0,ch);
                int tmp1 = p.left;
                int tmp2 = p.right;
                p.left++;
                p.right--;
                //System.out.println(sb1.toString()+sb2.toString());
                results.add(sb1.toString()+sb2.toString());
                dfs(results,nums.get(tmp1)+1,nums.get(tmp2)-1,sb1,sb2,keySet
,map,locations);
                sb1.deleteCharAt(sb1.length()-1);
                sb2.deleteCharAt(0);                    
            }
            p.left = oldLeft;
            p.right = oldRight;
        }
    }
}
这所有的回文字串有点难啊,我把mitbbs上的解法翻译成C++了. 1point3acres.com/bbs

#include <vector>
#include <iostream>
#include <string>
#include <map>. From 1point 3acres bbs
using namespace std;
鏉ユ簮涓€浜�.涓夊垎鍦拌鍧�. 
map<char, vector<int>> leftbook;
map<char, vector<int>> rightbook;

void fill(string s) {
    for (auto x : s) {
        if (leftbook.find(x) == leftbook.end())
            leftbook[x] = vector<int>(s.size(), -1);
        if (rightbook.find(x) == rightbook.end())
            rightbook[x] = vector<int>(s.size(), -1);
    }. visit 1point3acres.com for more.

    for (int i = 0; i < s.size(); ++i) {
        for (auto p = leftbook.begin(); p != leftbook.end(); ++p) {
            if (s == p->first)
                (p->second) = i;
            else 鏉ユ簮涓€浜�.涓夊垎鍦拌鍧�. 
                (p->second) = (i == 0 ? -1 : (p->second)[i-1]);
        }.鐣欏璁哄潧-涓€浜�-涓夊垎鍦�
    }. From 1point 3acres bbs

    for (int i = s.size() - 1; i >= 0; --i) {
        for (auto p = rightbook.begin(); p != rightbook.end(); ++p) {
            if (s == p->first). more info on 1point3acres.com
                (p->second) = i;
            else
                (p->second) = (i == s.size() - 1 ? -1 : (p->second)[i+1]);
        }
    }

}
-google 1point3acres
void fun(int l, int r, string half) {
    cout<<half + string(half.rbegin(), half.rend())<<endl;
    for (auto p = leftbook.begin(); p != leftbook.end(); ++p) {.鐣欏璁哄潧-涓€浜�-涓夊垎鍦�
        char c = p->first;
        int left = rightbook[c][l];
        int right = leftbook[c][r];
        if (left != -1 && left <= r) {.鏈枃鍘熷垱鑷�1point3acres璁哄潧
            cout<<half + c + string(half.rbegin(), half.rend())<<endl;
            if (right > left)
                fun(left + 1, right - 1, half + c);
        }
    }.鐣欏璁哄潧-涓€浜�-涓夊垎鍦�
}. visit 1point3acres.com for more.
鏉ユ簮涓€浜�.涓夊垎鍦拌鍧�. 
int main(int argc, char const *argv[])
{
    string s = "abcba";
    fill(s);
    fun(0, s.size() - 1, "");
    return 0;. from: 1point3acres.com/bbs 
}
补充内容 (2015-11-6 11:29):
leftbook是每个字符往左能看到的位置,rightbook是每个字符往右能看到的位置。
算法就是对所有的字符遍历并拼接起来。拼接的条件是,下一个字符必须落在上一个字符的两个book所规定的范围里


Labels

LeetCode (1432) GeeksforGeeks (1122) LeetCode - Review (1067) Review (882) Algorithm (668) to-do (609) Classic Algorithm (270) Google Interview (237) Classic Interview (222) Dynamic Programming (220) DP (186) Bit Algorithms (145) POJ (141) Math (137) Tree (132) LeetCode - Phone (129) EPI (122) Cracking Coding Interview (119) DFS (115) Difficult Algorithm (115) Lintcode (115) Different Solutions (110) Smart Algorithm (104) Binary Search (96) BFS (91) HackerRank (90) Binary Tree (86) Hard (79) Two Pointers (78) Stack (76) Company-Facebook (75) BST (72) Graph Algorithm (72) Time Complexity (69) Greedy Algorithm (68) Interval (63) Company - Google (62) Geometry Algorithm (61) Interview Corner (61) LeetCode - Extended (61) Union-Find (60) Trie (58) Advanced Data Structure (56) List (56) Priority Queue (53) Codility (52) ComProGuide (50) LeetCode Hard (50) Matrix (50) Bisection (48) Segment Tree (48) Sliding Window (48) USACO (46) Space Optimization (45) Company-Airbnb (41) Greedy (41) Mathematical Algorithm (41) Tree - Post-Order (41) ACM-ICPC (40) Algorithm Interview (40) Data Structure Design (40) Graph (40) Backtracking (39) Data Structure (39) Jobdu (39) Random (39) Codeforces (38) Knapsack (38) LeetCode - DP (38) Recursive Algorithm (38) String Algorithm (38) TopCoder (38) Sort (37) Introduction to Algorithms (36) Pre-Sort (36) Beauty of Programming (35) Must Known (34) Binary Search Tree (33) Follow Up (33) prismoskills (33) Palindrome (32) Permutation (31) Array (30) Google Code Jam (30) HDU (30) Array O(N) (29) Logic Thinking (29) Monotonic Stack (29) Puzzles (29) Code - Detail (27) Company-Zenefits (27) Microsoft 100 - July (27) Queue (27) Binary Indexed Trees (26) TreeMap (26) to-do-must (26) 1point3acres (25) GeeksQuiz (25) Merge Sort (25) Reverse Thinking (25) hihocoder (25) Company - LinkedIn (24) Hash (24) High Frequency (24) Summary (24) Divide and Conquer (23) Proof (23) Game Theory (22) Topological Sort (22) Lintcode - Review (21) Tree - Modification (21) Algorithm Game (20) CareerCup (20) Company - Twitter (20) DFS + Review (20) DP - Relation (20) Brain Teaser (19) DP - Tree (19) Left and Right Array (19) O(N) (19) Sweep Line (19) UVA (19) DP - Bit Masking (18) LeetCode - Thinking (18) KMP (17) LeetCode - TODO (17) Probabilities (17) Simulation (17) String Search (17) Codercareer (16) Company-Uber (16) Iterator (16) Number (16) O(1) Space (16) Shortest Path (16) itint5 (16) DFS+Cache (15) Dijkstra (15) Euclidean GCD (15) Heap (15) LeetCode - Hard (15) Majority (15) Number Theory (15) Rolling Hash (15) Tree Traversal (15) Brute Force (14) Bucket Sort (14) DP - Knapsack (14) DP - Probability (14) Difficult (14) Fast Power Algorithm (14) Pattern (14) Prefix Sum (14) TreeSet (14) Algorithm Videos (13) Amazon Interview (13) Basic Algorithm (13) Codechef (13) Combination (13) Computational Geometry (13) DP - Digit (13) LCA (13) LeetCode - DFS (13) Linked List (13) Long Increasing Sequence(LIS) (13) Math-Divisible (13) Reservoir Sampling (13) mitbbs (13) Algorithm - How To (12) Company - Microsoft (12) DP - Interval (12) DP - Multiple Relation (12) DP - Relation Optimization (12) LeetCode - Classic (12) Level Order Traversal (12) Prime (12) Pruning (12) Reconstruct Tree (12) Thinking (12) X Sum (12) AOJ (11) Bit Mask (11) Company-Snapchat (11) DP - Space Optimization (11) Dequeue (11) Graph DFS (11) MinMax (11) Miscs (11) Princeton (11) Quick Sort (11) Stack - Tree (11) 尺取法 (11) 挑战程序设计竞赛 (11) Coin Change (10) DFS+Backtracking (10) Facebook Hacker Cup (10) Fast Slow Pointers (10) HackerRank Easy (10) Interval Tree (10) Limited Range (10) Matrix - Traverse (10) Monotone Queue (10) SPOJ (10) Starting Point (10) States (10) Stock (10) Theory (10) Tutorialhorizon (10) Kadane - Extended (9) Mathblog (9) Max-Min Flow (9) Maze (9) Median (9) O(32N) (9) Quick Select (9) Stack Overflow (9) System Design (9) Tree - Conversion (9) Use XOR (9) Book Notes (8) Company-Amazon (8) DFS+BFS (8) DP - States (8) Expression (8) Longest Common Subsequence(LCS) (8) One Pass (8) Quadtrees (8) Traversal Once (8) Trie - Suffix (8) 穷竭搜索 (8) Algorithm Problem List (7) All Sub (7) Catalan Number (7) Cycle (7) DP - Cases (7) Facebook Interview (7) Fibonacci Numbers (7) Flood fill (7) Game Nim (7) Graph BFS (7) HackerRank Difficult (7) Hackerearth (7) Inversion (7) Kadane’s Algorithm (7) Manacher (7) Morris Traversal (7) Multiple Data Structures (7) Normalized Key (7) O(XN) (7) Radix Sort (7) Recursion (7) Sampling (7) Suffix Array (7) Tech-Queries (7) Tree - Serialization (7) Tree DP (7) Trie - Bit (7) 蓝桥杯 (7) Algorithm - Brain Teaser (6) BFS - Priority Queue (6) BFS - Unusual (6) Classic Data Structure Impl (6) DP - 2D (6) DP - Monotone Queue (6) DP - Unusual (6) DP-Space Optimization (6) Dutch Flag (6) How To (6) Interviewstreet (6) Knapsack - MultiplePack (6) Local MinMax (6) MST (6) Minimum Spanning Tree (6) Number - Reach (6) Parentheses (6) Pre-Sum (6) Probability (6) Programming Pearls (6) Rabin-Karp (6) Reverse (6) Scan from right (6) Schedule (6) Stream (6) Subset Sum (6) TSP (6) Xpost (6) n00tc0d3r (6) reddit (6) AI (5) Abbreviation (5) Anagram (5) Art Of Programming-July (5) Assumption (5) Bellman Ford (5) Big Data (5) Code - Solid (5) Code Kata (5) Codility-lessons (5) Coding (5) Company - WMware (5) Convex Hull (5) Crazyforcode (5) DFS - Multiple (5) DFS+DP (5) DP - Multi-Dimension (5) DP-Multiple Relation (5) Eulerian Cycle (5) Graph - Unusual (5) Graph Cycle (5) Hash Strategy (5) Immutability (5) Java (5) LogN (5) Manhattan Distance (5) Matrix Chain Multiplication (5) N Queens (5) Pre-Sort: Index (5) Quick Partition (5) Quora (5) Randomized Algorithms (5) Resources (5) Robot (5) SPFA(Shortest Path Faster Algorithm) (5) Shuffle (5) Sieve of Eratosthenes (5) Strongly Connected Components (5) Subarray Sum (5) Sudoku (5) Suffix Tree (5) Swap (5) Threaded (5) Tree - Creation (5) Warshall Floyd (5) Word Search (5) jiuzhang (5)

Popular Posts