Showing posts with label Dynamic Languages. Show all posts
Showing posts with label Dynamic Languages. Show all posts

Palindrome - How to Succeed in Algorithms Interview


Palindrome - How to Succeed in Algorithms Interview

How to Succeed in Algorithms Interview Series


Palindrome

  • O(N^2) DP or DFS+cache
  • DFS + cache: easier to write
  • or DP: use len
    • int[][] palindromeLen, boolean[][] isPalindrome; int j = i + len (- 1);
  • expand at center expansion
  • freqMap
  • build palindrome
  • Case: odd or ven length
  • reverse

DP

minimum inserts:
I[i..j] = I[i+1..j-1], if S[i] = S[j]
I[i..j] = min{I[i..j-1], I[i+1..j]}+1, otherwise.

Base Case :  
I[i,i] = 0, as a single character itself is a palindrome.
L[k][j] = str.charAt(k) == str.charAt(j) ? L[k + 1][j - 1] : Math.min(L[k][j - 1], L[k + 1][j]) + 1;
Minimum deletes
d[i..j] = d[i+1..j-1], if d[i] = d[j] (i.e. no deletions required)
d[i..j] = min{d[i..j-1], d[i-1..j]}+1, otherwise. (i.e. one deletion required)

Base Case :  
d[i,i] = i
d[0,j] = j

Expand at Center

  OPT(i,j) = 2 + OPT(i+1, j-1) if A[i] = A[j],
           = max (OPT(i,j-1), OPT(i+1,j), otherwise.
private int lo, maxLen;
public String longestPalindrome(String s) {
    int len = s.length();
    if (len < 2)
        return s;
    for (int i = 0; i < len-1; i++) {
        extendPalindrome(s, i, i);  //assume odd length, try to extend Palindrome as possible
        extendPalindrome(s, i, i+1); //assume even length.
    }
    return s.substring(lo, lo + maxLen);
}
private void extendPalindrome(String s, int j, int k) {
    while (j >= 0 && k < s.length() && s.charAt(j) == s.charAt(k)) {
        j--;
        k++;
    }
    if (maxLen < k - j - 1) {
        lo = j + 1;
        maxLen = k - j - 1;
    }
}
public int minCut(String s) {
    char[] c = s.toCharArray();
    int n = c.length;
    int[] cut = new int[n];
    boolean[][] pal = new boolean[n][n];
    for(int i = 0; i < n; i++) {
        int min = i;
        for(int j = 0; j <= i; j++) {
            if(c[j] == c[i] && (j + 1 > i - 1 || pal[j + 1][i - 1])) {
                pal[j][i] = true;  
                min = j == 0 ? 0 : Math.min(min, cut[j - 1] + 1);
            }
        }
        cut[i] = min;
    }
    return cut[n - 1];
}

public int minCut(String s) {
    if(s==null || s.length()<2){
        return 0;
    }
    int n = s.length();
    char[] t = s.toCharArray();
    int[] dp = new int[n+1];
    Arrays.fill(dp,Integer.MAX_VALUE);
    dp[0] = -1;
    int i = 0;
    while(i<n){
        expand(t,dp,i,i);
        expand(t,dp,i,i+1);
        i++;
    }
    return dp[n];
}
private void expand(char[] t,int[] dp,int i,int j){
    while(i>=0 && j<t.length && t[i] == t[j]){
        dp[j+1] = Math.min(dp[j+1],dp[i] + 1);
        i--;j++;
    }
}

Build Palindrome

freqMap

public int check(String str) {
 HashMap<Character, Integer> map = new HashMap<Character, Integer>();
 for (int i=0; i<str.length(); i++) {
     char c = str.charAt(i);
     if (map.containsKey(c)) {
         map.put(c, map.get(c)+1);
     }
     else {
         map.put(c, 1);
      }
  }

  int cntOdd = 0;
  for (int val : map.values()) {
      if (val % 2 == 1) {
          cntOdd++;
      }
  }
  return cntOdd>1? 0 : 1;
}

Two Pointers

public int countChunk(String str) {
 if (str==null || str.length()==0) return 0;
 int sum = 0;
 int l=0, r=str.length()-1;
 int preL = l, preR = r;
 while (l < r) {
   String left = str.substring(preL, l+1);
   String right = str.substring(r, preR+1);
   if (left.equals(right)) {
       preL = l+1;
       preR = r-1;
       sum += 2;
   }
   l++;
   r--;
}
 if (preL <= preR) sum+=1;
 return sum;
}

Reverse

Build Palindrome

Examples

Use xargs to Pipe Output to Script As Command Line Argument


Use xargs to Pipe Output to Script As Command Line Argument

A script normally accepts command line argument and also accepts output from another script as parameters.
say two perl scripts:
a.pl:
#!/usr/bin/perl
print "1\n2\n3\n";

b.pl
#!/usr/bin/perl
my $argc = 0;
foreach my $arg (@ARGV) {
    printf "Argument %2d: '%s'\n", ++ $argc, $arg;
}

In Linux, we can use xargs to pipe output of one command as command line argument of another command, like:
a.pl | xargs b.pl
a.pl | xargs b.pl 4 5 6

But seems there is no such command like xargs in Windows.
Still need find a way to support pipe output to script as command line argument in Windows.
or find how to implement this function directly in Perl script.

Programming Principles




Generic
KISS (Keep It Simple Stupid)
YAGNI
Do The Simplest Thing That Could Possibly Work
Separation of Concerns
Keep Things DRY
Code For The Maintainer
Avoid Premature Optimization
Boy-Scout Rule
- Leave the campground cleaner than you found it


Inter-Module/Class
Minimise Coupling
Composition Over Inheritance
Orthogonality
Robustness Principle
Be conservative in what you do, be liberal in what you accept from others
Inversion of Control
- Don’t call us, we’ll call you

Module/Class
Maximise Cohesion
Liskov Substitution Principle
Open/Closed Principle

Single Responsibility Principle
- A class should never have more than one reason to change.

Hide Implementation Details
Curly’s Law
Encapsulate What Changes

Interface Segregation Principle
- Reduce fat interfaces into multiple smaller and more specific client specific interfaces.

Command Query Separation
- Asking a question should not modify the answer
- Separating methods into queries and commands

SOLID
- Liskov Substitution Principle

Resources

Labels

ANT (6) Algorithm (69) Algorithm Series (35) Android (7) Big Data (7) Blogger (14) Bugs (6) Cache (5) Chrome (19) Code Example (29) Code Quality (7) Coding Skills (5) Database (7) Debug (16) Design (5) Dev Tips (63) Eclipse (32) Git (5) Google (33) Guava (7) How to (9) Http Client (8) IDE (7) Interview (88) J2EE (13) J2SE (49) JSON (7) Java (186) JavaScript (27) Learning code (9) Lesson Learned (6) Linux (26) Lucene-Solr (112) Mac (10) Maven (8) Network (9) Nutch2 (18) Performance (9) PowerShell (11) Problem Solving (11) Programmer Skills (6) Scala (6) Security (9) Soft Skills (38) Spring (22) System Design (11) Testing (7) Text Mining (14) Tips (17) Tools (24) Troubleshooting (29) UIMA (9) Web Development (19) Windows (21) adsense (5) bat (8) regex (5) xml (5)