Monday, May 18, 2015

Longest Palindromic Substring

来源:Leetcode

原帖:http://oj.leetcode.com/problems/longest-palindromic-substring/

题目:
Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.

代码:
 class Solution {  
 public:  
   string longestPalindrome(string s) {  
     int N = s.length();  
     int start = 0, maxlen = 0;  
     for (int center = 0; center < N; center++) {  
       expand(s, center, center, maxlen, start);  
       expand(s, center, center + 1, maxlen, start);  
     }  
     return s.substr(start, maxlen);  
   }  
     
   void expand(const string& s, int left, int right, int& maxlen, int& start){  
     while (left >= 0 && right < s.length() && s[left] == s[right]) {  
       left--;   
       right++;  
     }  
     if (right - left - 1 > maxlen) {  
       maxlen = right - left - 1;  
       start = left + 1;  
     }  
   }  
 };  

Interleaving String

来源:Leetcode

原帖:http://oj.leetcode.com/problems/interleaving-string/

题目:
Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.
For example,
Given:
s1 = "aabcc",
s2 = "dbbca",
When s3 = "aadbbcbcac", return true.
When s3 = "aadbbbaccc", return false.

Solution: 1. dp. O(MN) time & space. 'dp[i][j] == true' means that there is at least one way to construct the string s3[0...i+j-1] by interleaving s1[0...j-1] and s2[0...i-1].

代码:
 class Solution {  
 public:  
   //Version 1: dp  
   bool isInterleave(string s1, string s2, string s3) {  
     int M = s1.size(), N = s2.size(), K = s3.size();  
     if (M + N != K) return false;  
     if (s1.empty()) return s2 == s3; // corner case  
     if (s2.empty()) return s1 == s3;  
     vector<vector<bool> > dp(N + 1, vector<bool>(M + 1, false));  
     for (int i = 1; i <= N; ++i)  
       dp[i][0] = s2[i - 1] == s3[i - 1];  
     for (int j = 1; j <= M; ++j)  
       dp[0][j] = s1[j - 1] == s3[j - 1];        
     for (int i = 1; i <= N; ++i) {  
       for (int j = 1; j <= M; ++j) {  
         dp[i][j] = dp[i - 1][j] && s2[i - 1] == s3[i + j - 1] ||  
               dp[i][j - 1] && s1[j - 1] == s3[i + j - 1];          
       }  
     }  
     return dp[N][M];  
   }  
 };  

Palindrome Partitioning II

来源:Leetcode

原帖:https://oj.leetcode.com/problems/palindrome-partitioning-ii/

题目:
Given a string s, partition s such that every substring of the partition is a palindrome. Return the minimum cuts needed for a palindrome partitioning of s.
For example, given s = "aab",
Return 1 since the palindrome partitioning ["aa","b"] could be produced using 1 cut.

代码:
 class Solution {  
 public:  
   int minCut(string s) {  
     int N = s.size();  
     // isP[0]: [0,i] is palindrome  
     bool isP[N]; // [j,i] is palindrome; j = [0, 1, ..., i-1]  
     int dp[N];  
     dp[0] = 0;  
     for (int i = 1; i < N; ++i) { // end point  
       isP[i] = true;  
       dp[i] = dp[i-1] + 1; // dp[i-1] + single word cut  
       for (int j = 0; j < i; ++j) {  
         isP[j] = (s[i] == s[j]) ? isP[j+1] : false; // isP[j] == true  -> [j...i] is a palindrome; ascending order  
                           // isP[j+1] == true -> [j+1...i-1] is a palindrome  
         if (isP[j]) {  
           dp[i] = (j == 0) ? 0 : min(dp[i], dp[j-1] + 1); // dp[i] -> minCount for [0...i]            
         }  
       }  
     }  
     return dp[N-1];  
   }  
 };  
   
 // Time Limit Exceed  
 class Solution {  
 public:  
   //Version 2: sequence dp; easier to understand isP  
   void getIsPalindrome(const string &s, vector<vector<bool> > &isP) {  
     int N = s.size();  
     // isP[i][j] (start i, end j is palindrome)  
     for (int i = 0; i < N; ++i) {  
       isP[i][i] = true;        
     }  
     for (int l = 2; l <= N; ++l) {  
       for (int i = 0; i <= N - l; ++i) {  
         isP[i][i + l - 1] = false;  
         if (l == 2) {  
           isP[i][i + l - 1] = (s[i] == s[i + 1]);  
         } else {  
           isP[i][i + l - 1] = (s[i] == s[i + l - 1] && isP[i + 1][i + l - 2]);  
         }    
       }  
     }  
   }  
   
   int minCut(string s) {  
     int N = s.size();  
     vector<vector<bool>> isP(N, vector<bool>(N, false));  
     getIsPalindrome(s, isP);  
     vector<int> dp(N, 0);  
     dp[0] = 0;  
     for (int i = 1; i < N; ++i) {  
       dp[i] = dp[i - 1] + 1;  
       for (int j = 0; j < i; ++j) {  
         if (j == 0 && isP[j][i]) {  
           dp[i] = 0;   
           break;  
         } else if (isP[j][i]) {  
           dp[i] = min(dp[i], dp[j - 1] + 1);  
         }  
       }  
     }  
     return dp[N - 1];  
   }  
 };  


Palindrome Partitioning I

来源:Leetcode

原帖:https://oj.leetcode.com/problems/palindrome-partitioning/

题目:
Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s.
For example, given s = "aab",
Return
 [
  ["aa","b"],
  ["a","a","b"]
 ]

代码:
 class Solution {  
 public:  
   bool isPalindrome(const string &s) {  
     int i = 0, j = s.size()-1;  
     while (i < j) {  
       if (s[i] != s[j]) return false;  
       i++; j--;  
     }  
     return true;  
   }  
   
   void partitionHelper(const string &s, int start, vector<string> &path, vector<vector<string> >& res) {  
     if (start == s.size()) {  
       res.push_back(path);  
       return;  
     }  
     string palindrom;  
     for (int i = start; i < s.size(); ++i) {  
       palindrom.push_back(s[i]);  
       if (isPalindrome(palindrom)) {  
         path.push_back(palindrom);  
         partitionHelper(s, i + 1, path, res);  
         path.pop_back();           
       }  
     }  
   }  
   
   vector<vector<string>> partition(string s) {  
     vector<string> path;  
     vector<vector<string> > res;  
     partitionHelper(s, 0, path, res);  
     return res;  
   }  
 };  


Scramble String

来源:Leetcode

原帖:http://oj.leetcode.com/problems/scramble-string/

题目:
Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively.
Below is one possible representation of s1 = "great":
       great
      /     \
     gr    eat
    / \    /  \
   g   r  e   at
              / \
             a   t
To scramble the string, we may choose any non-leaf node and swap its two children. For example, if we choose the node "gr" and swap its two children, it produces a scrambled string "rgeat".
       rgeat
      /     \
     rg    eat
    / \    /  \
   r   g  e   at
              / \
             a   t
We say that "rgeat" is a scrambled string of "great". Similarly, if we continue to swap the children of nodes "eat" and "at", it produces a scrambled string "rgtae".
      rgtae
      /    \
     rg    tae
    / \    /  \
   r   g  ta  e
          / \
         t   a
We say that "rgtae" is a scrambled string of "great". Given two strings s1 and s2 of the same length, determine if s2 is a scrambled string of s1.
Solution: 1. 3-dimensional dp.
              'dp[k][i][j] == true' means string s1(start from i, length k) is a scrambled string of
              string s2(start from j, length k).

代码:
 class Solution {  
 public:  
   bool isScramble(string s1, string s2) {  
     if(s1.size() != s2.size()) return false;  
     int N = s1.size();  
     bool dp[N + 1][N][N];  
     for (int k = 1; k <= N; ++k) { // string length k  
       for (int i = 0; i <= N-k; ++i) { // start i  
         for (int j = 0; j <= N-k; ++j) { // start j   
           dp[k][i][j] = false;  
           if (k == 1)  
             dp[1][i][j] = (s1[i] == s2[j]);    
           for (int p = 1; p < k; ++p) { // 把树分成两子树,如果满足scramble,则分成的两个子树一定是scramble  
             if (dp[p][i][j] && dp[k - p][i + p][j + p]   
              || dp[p][i][j + k - p] && dp[k - p][i + p][j]) {  
               dp[k][i][j] = true;   
               break;              
             }  
           }  
         }  
       }  
     }  
     return dp[N][0][0];  
   }  
 };  


Longest Increasing Box

来源:cc150, itint5

原帖:http://www.itint5.com/oj/#34

题目:
有n块积木,每块积木有体积vol和重量weight两个属性,用二元组(vol, weight)表示。积木需要搭成竖直的塔状,上面积木的体积和重量必须都比它下面的积木小。问最多可以搭多少个积木。样例:
有7个积木boxes:
 [(65, 100), (70, 150), (56, 90), (75, 190), (60, 95), (68, 110), (80, 12)]
最多可以搭6个积木,从上到下分别为:
 (56, 90), (60, 95), (65, 100), (68, 110), (70, 150), (75, 190)
所以函数应该返回6。

题目来源:CRACKING THE CODING INTERVIEW 9.7
Solution: 先按照vol进行排序,题目就变成了根据weight寻找最长严格递增子序列。

代码:
 /*积木的定义(请不要在代码中定义该结构)  
 struct Box {  
  int vol, weight;  
 };*/  
    
 int mycompare(const Box& a, const Box& b) {  
   if (a.vol == b.vol)  
     return a.weight < b.weight;  
   return a.vol < b.vol;  
 }  
   
 int maxBoxes(vector<Box> &boxes) {  
   int N = boxes.size();  
   if (N == 0) return 0;  
   sort(boxes.begin(), boxes.end(), mycompare);  
   vector<int> dp(N, 0);  
   int res = 1;  
   for (int i = 0; i < N; ++i) {  
     dp[i] = 1;  
     for (int j = 0; j < i; ++j)  
       if (boxes[i].vol > boxes[j].vol && boxes[i].weight > boxes[j].weight)  
         dp[i] = max(dp[i], dp[j] + 1);  
     res = max(res, dp[i]);  
   }  
   return res;  
 }  

Minimum Path Sum

来源:Leetcode

原帖:http://oj.leetcode.com/problems/minimum-path-sum/

题目:
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.
Solution: Dynamic Programming. Space O(N).

代码:
 class Solution {  
 public:  
   int minPathSum(vector<vector<int> > &grid) {  
     if (grid.empty()) return INT_MIN;  
     int M = grid.size(), N = grid[0].size(); // col  
     vector<int> dp(N, 0);  
     dp[0] = grid[0][0];  
     for (int i = 1; i < N; ++i) {  
       dp[i] = grid[0][i] + dp[i - 1];        
     }      
     for (int i = 1; i < M; ++i) { // row  
       dp[0] += grid[i][0];  
       for (int j = 1; j < N; ++j) { // col  
         dp[j] = min(dp[j - 1], dp[j]) + grid[i][j];  
       }  
     }  
     return dp[N - 1];  
   }  
 };