📣 独立日限时特惠: VIP通行证立减$68
楼主: jaly50
跳转到指定楼层
上一主题 下一主题
收起左侧

[Leetcode] Leetcode个人刷题思路和自我督促贴

🔗
 楼主| jaly50 2014-12-13 07:40:04 | 只看该作者
全局:
  1. import java.util.Arrays;
  2. import java.util.Stack;
  3. /*
  4. * LeetCode: 137  Simplify Path
  5. * Author: Scarlett
  6. * 字符串处理题,要用到string.split
  7. * 主要是处理 . 和..的情况
  8. * 用stack增加和删除路径
  9. *
  10. * 第一遍没过是因为没有考虑 //的情况下,split会分配给它一个 length=0的string  ---要注理掉
  11. */

  12. public class SimplifyPath {
  13.          public String simplifyPath(String path) {
  14.                 if (path==null || path.length()==0) return path;
  15.                 Stack<String> s = new Stack<String>();
  16.                 String[] pos = path.split("/");
  17.              //   System.out.println(Arrays.toString(pos));
  18.                 for (int i =0 ; i< pos.length; i++) {
  19.                     if (pos[i].equals(".") || pos[i].length()==0) {
  20.                         continue;
  21.                     }
  22.                     else if (pos[i].equals("..")) {
  23.                         if (!s.isEmpty()) s.pop();
  24.                     }
  25.                     else {
  26.                         s.push(pos[i]);
  27.                     }
  28.                 }
  29.                 StringBuffer ans = new StringBuffer();
  30.                 while (!s.isEmpty()) {
  31.                         ans.insert(0, '/'+s.pop());
  32.                 }
  33.                 if (ans.length()==0) ans.append('/');
  34.                 return ans.toString();
  35.             }
  36.         public static void main(String[] args) {
  37.                 // TODO Auto-generated method stub
  38.                 SimplifyPath s = new SimplifyPath();
  39.                 System.out.println(s.simplifyPath("/..."));
  40.         }

  41. }
复制代码
回复

使用道具 举报

🔗
 楼主| jaly50 2014-12-13 09:02:54 | 只看该作者
全局:
  1. import java.util.Arrays;
  2. /*
  3. * Leetcode 137 Set Matrix Zeroes
  4. * Author: Scarlett
  5. * 要求:Did you use extra space?
  6. A straight forward solution using O(mn) space is probably a bad idea.
  7. A simple improvement uses O(m + n) space, but still not the best solution.
  8. Could you devise a constant space solution?

  9.   这道题常见的误区可能是 会在matrix里直接改值,这样会导致错误。比如我因为matrix[1][2]==0,
  10.   就把row[1] col[2]全设零,那么当数组遍历到 matrix[other number][2]时,也会把相应行全设为零。这就不是我们要的。
  11.   
  12.   O(mn)的方法很直接,就是再设一个boolean或int二维数组,用original的数组去判断是否修改,用新数组存改后的值
  13.   o(m+n)的方法就是下面第一个, 用两个boolean数组(长度分别为m和n)判断该行或该列是否已被设为零
  14.   
  15.   O(1)的方法,这个不错:https://oj.leetcode.com/discuss/16190/is-there-any-constant-space-solution-with-just-one-pass

  16. */

  17. public class SetMatrixZeroes {
  18.         /*
  19.          *  extra space: o(m+n)
  20.          *  用两个boolean数组(长度分别为m和n)判断该行或该列是否已被设为零
  21.          *  Date: 12/12/2014 Fri 7:15 PM
  22.          */
  23.     public void setZeroes_OmPlusN(int[][] matrix) {
  24.         int n = matrix.length;
  25.         if (n==0) return;
  26.         int m = matrix[0].length;
  27.         boolean[] rowIsZero = new boolean[n];  
  28.         boolean[] colIsZero = new boolean[m];
  29.         Arrays.fill(rowIsZero, false);
  30.         Arrays.fill(colIsZero, false);
  31.         for (int i=0; i<n; i++) {
  32.             for (int j=0; j<m; j++) {
  33.                 if (matrix[i][j]==0) {
  34.                     rowIsZero[i] = true;
  35.                     colIsZero[j] = true;
  36.                 }
  37.             }
  38.         }
  39.         for (int i=0; i<n; i++) {
  40.             for (int j=0; j<m; j++) {
  41.                 if (rowIsZero[i] || colIsZero[j]) {
  42.                     matrix[i][j] = 0;
  43.                 }
  44.             }
  45.         }
  46.         return;
  47.       }
  48.    
  49.     /*   本来以为constant space solution可以用位运算,放两个字符串,分别代表row和col,每个数的每一位都代表具体的某一行或某一列,值可能有0或1
  50.    其实就是利用了发现o(m+n)的方法里多的数组的值其实只有0和1  才能再进一步升级为位运算
  51.      * 于是试图用bit operation写...
  52.       发现n和m的长度超出20位...要用string的话。。我觉得就和上面那个O(m+n)没有什么本质区别了
  53.       宣告失败= =
  54.    */
  55.     public void setZeroes_bitOperation_fail(int[][] matrix) {
  56.         int n = matrix.length;
  57.         if (n==0) return;
  58.         int m = matrix[0].length;
  59.         long rowIsZero = 0;  
  60.         long colIsZero = 0;
  61.         for (int i=0; i<n; i++) {
  62.             for (int j=0; j<m; j++) {
  63.                 if (matrix[i][j]==0) {
  64.                     rowIsZero |= 1<<i;
  65.                     colIsZero |= 1<<j;
  66.                 }
  67.             }
  68.         }
  69.         for (int i=0; i<n; i++) {
  70.             for (int j=0; j<m; j++) {
  71.                 if ((rowIsZero & 1<<i) !=0 || (colIsZero &1<<j) !=0) {
  72.                     matrix[i][j] = 0;
  73.                 }
  74.             }
  75.         }
  76.         return;
  77.       }
  78.         public static void main(String[] args) {
  79.                 // TODO Auto-generated method stub

  80.         }

  81. }
复制代码
回复

使用道具 举报

🔗
 楼主| jaly50 2014-12-13 11:03:13 | 只看该作者
全局:
本帖最后由 jaly50 于 2014-12-13 11:13 编辑
  1. /*
  2. * LeetCode 139 Permutation Sequence
  3. * Author: Scarlett
  4. * Date: 12/12/2014 Fri 9:55 PM
  5. * 得到长度为n的第k个排列。
  6. * 我的方法是研究k个排列的规律,比如 1-6之间,就只有最后3位变化。
  7. * 所以我先把 k=k-max(x!<k)  (1<x<n), 同时得到x位的新值,把x后面的值往后挪。重复这样做,就可以得到第K个值。
  8. * 有点儿算是十进制换成二进制的思路呢。如65>64,就先把第6位的值改为1。
  9. * 更复杂一点点,因为这里不只有1和0两种变化。
  10. * 2!=2 ,3!=6  如果k是5的话,就要减去2次的2,于是第三位的值就会加两次,变成3.  
  11. *
  12. * 和别人的思路差不多,但是人家用recursive的方法,清楚简单多了:https://oj.leetcode.com/discuss/5568/does-anyone-have-better-idea-share-accepted-python-code-here
  13. */
  14. public class PermutationSequence {
  15. public String getPermutation(int n, int k) {
  16.         StringBuffer ans = new StringBuffer();
  17.         for (int i=1; i<=n; i++)
  18.                 ans.append(i);
  19.         k= k-1; //The current one is the first one. So we make it begin from 0
  20.         while (k>0) {
  21.         int pos =1;
  22.         int maxValue = 1;
  23.         //求最大阶乘
  24.         while (maxValue * pos <= k) {
  25.                 maxValue = maxValue * pos++;
  26.         }
  27.         char posValue, newPosValue;
  28.         posValue = ans.charAt(n-pos);
  29.         newPosValue= posValue;
  30.         int posOld, posNew;
  31.         posOld = n-pos;
  32.         posNew = posOld;
  33.         //算算有多少 (x-1)!的变化,当前位的值就要从后面几个拿。
  34.         //其实是取商和取余的过程= =
  35.         while (k>=maxValue) {
  36.         k = k - maxValue;
  37.         posNew++;
  38.         }
  39.         newPosValue = ans.charAt(posNew);
  40.         
  41.         ans.deleteCharAt(posNew);
  42.         ans.insert(posOld,newPosValue);
  43.         
  44.       //  System.out.println("maxValue= "+maxValue+" k="+k+" pos= "+ pos+" s1= "+newPosValue+" s2= "+posValue+"  --> "+ans.toString());
  45.         }
  46.      return ans.toString();        
  47.     }

  48.         public static void main(String[] args) {
  49.                 // TODO Auto-generated method stub
  50.                 char v ='1';
  51.                 //System.out.println(++v);
  52.                 PermutationSequence p = new PermutationSequence();
  53.                 System.out.println(p.getPermutation(3, 1));
  54.                 System.out.println(p.getPermutation(3, 4));
  55.         }

  56. }
复制代码
回复

使用道具 举报

🔗
 楼主| jaly50 2014-12-13 12:50:52 | 只看该作者
全局:
  1. import java.util.ArrayList;
  2. import java.util.List;
  3. /*
  4. * LeetCode 140 Restore IP Addresses
  5. * Author: Scarlett chen
  6. * Date: 12/12/2014 Fri 11:48 PM
  7. * 完成今天5题刷题任务:D
  8. * 这题用搜索...比较经典简单直接~
  9. * 第一次没有过:是少考虑了 不能“00”的情况
  10. * 其他情况要考虑的是: 每个field不能多于3位数,也不能少于1位数; 数字必须在0到255之间。
  11. */



  12. public class RestoreIP {
  13.         List<String> ans;
  14.     public List<String> restoreIpAddresses(String s) {
  15.         ans = new ArrayList<String>();
  16.         int len = s.length();
  17.         if (len >12 || len<4) {
  18.             return ans;
  19.         }
  20.         search(1,len,s,"");
  21.         return ans;
  22.     }
  23.     private void search(int curField, int digitsLeft, String s, String path) {  
  24.             int fieldsLeft = 4 - curField;
  25.             if (fieldsLeft <0 ) {
  26.                     ans.add(path.substring(0, path.length()-1));
  27.             }
  28.         for (int i=1; i<=3; i++) {
  29.             //Make the leftDigits is enough for leftFields,but not too much
  30.           if (digitsLeft-i < fieldsLeft) {
  31.               break;
  32.           }
  33.           else
  34.           if (3 * fieldsLeft + i < digitsLeft) {
  35.               continue;
  36.           }
  37.           else {
  38.               String fieldValue = s.substring(0, i);
  39.               if (fieldValue.length()>1) {
  40.                       if (fieldValue.charAt(0)=='0') continue;
  41.               }
  42.               int value = Integer.parseInt(fieldValue);
  43.               if (value >=0 && value <=255)
  44.               search(curField+1,digitsLeft-i, s.substring(i), path+fieldValue+".");
  45.           }
  46.         }
  47.          
  48.       }
  49.         public static void main(String[] args) {
  50.                 // TODO Auto-generated method stub
  51.                 RestoreIP ri = new RestoreIP();
  52.                 System.out.println(ri.restoreIpAddresses("2502510035"));
  53.         }

  54. }
复制代码
回复

使用道具 举报

🔗
 楼主| jaly50 2014-12-15 02:39:01 | 只看该作者
全局:
  1. /*
  2. * Time:12/14/2014 Sun 1:34 PM
  3. * Author: Scarlett Chen
  4. * LeetCode 145 Subsets II
  5. * 题本身不难,比非duplicate就是多两行判重的代码~
  6. * 要注意的就是path加了以后,要记得删掉~因为它是object,在method里call的时候不会自己变值
  7. *
  8. */

  9. import java.util.ArrayList;
  10. import java.util.Arrays;
  11. import java.util.List;


  12. public class SubSet2 {
  13.          List<List<Integer>> ans;
  14.          int[] num;
  15.          int len;
  16.         public List<List<Integer>> subsetsWithDup(int[] num) {
  17.                 Arrays.sort(num);
  18.         ans = new ArrayList<List<Integer>>();
  19.         this.num = num;
  20.         this.len = num.length;
  21.         ans.add(new ArrayList<Integer>());
  22.         List<Integer> path= new ArrayList<Integer>();
  23.       
  24.             for (int i=0; i < len; i++) {
  25.                      for (int count=1; count<=len-i; count++) {
  26.                     
  27.                     if (i>0 && num[i]==num[i-1]) continue;
  28.                 path = new ArrayList<Integer>();
  29.                 search(i,count,path);
  30.             }
  31.         }
  32.         return ans;
  33.         
  34.     }
  35.     private void search (int index, int countLeft,  List<Integer> path) {
  36.         if (countLeft==1) {
  37.             path.add(num[index]);
  38.           // System.out.println("Ans "+path);
  39.             ans.add(new ArrayList<Integer>(path));
  40.             path.remove(path.size()-1);
  41.             return;
  42.         }
  43.         else {
  44.              path.add(num[index]);
  45.               for (int i=index+1; i<len; i++) {
  46.                       if (i>index+1 && num[i]==num[i-1]) continue;
  47.                      // System.out.println(path+ " countLeft="+countLeft);
  48.                   search(i, countLeft-1, path);
  49.               }
  50.               path.remove(path.size()-1);
  51.             }
  52.         }
  53.    
  54.         public static void main(String[] args) {
  55.                 // TODO Auto-generated method stub
  56.                 SubSet2 s= new SubSet2();
  57.                 //System.out.println(s.subsetsWithDup(new int[]{}));
  58.                 //System.out.println(s.subsetsWithDup(new int[]{1}));
  59.                 //System.out.println(s.subsetsWithDup(new int[]{1,2}));
  60.                 //System.out.println(s.subsetsWithDup(new int[]{2,1,1}));
  61.                 System.out.println(s.subsetsWithDup(new int[]{1,2,3}));

  62.         }

  63. }
复制代码
回复

使用道具 举报

🔗
 楼主| jaly50 2014-12-15 05:27:26 | 只看该作者
全局:
  1. /*
  2. * LeetCode  Partition List
  3. * Author: Scarlett Chen
  4. * Time:12/14/2014 Sun 4:25 PM
  5. * 解法就是再建一个list放较大值,最后再拼接
  6. * 需要注意的就是把一个数挪给较大的list时,要让turn.next=null
  7. */
  8. public class Partition {
  9.     public ListNode partition(ListNode head, int x) {
  10.         if (head==null || head.next==null) return head;
  11.         ListNode second = new ListNode(-1);
  12.         ListNode first= new ListNode(-1);
  13.         ListNode secondHead = second;
  14.         ListNode firstHead = first;
  15.         first.next = head;
  16.         while (first.next!=null) {
  17.            if (first.next.val < x) {
  18.               first = first.next;
  19.            }
  20.            else {
  21.                    ListNode turn = first.next;
  22.                first.next = turn.next;
  23.                turn.next = null;
  24.                second.next = turn;
  25.                second = second.next;
  26.                
  27.            }
  28.            
  29.         }
  30.         first.next = secondHead.next;
  31.         return firstHead.next;  
  32.     }
  33.         public static void main(String[] args) {
  34.                 // TODO Auto-generated method stub
  35.                 Partition p = new Partition();
  36.                 ListNode head =new ListNode(1);
  37.                 head.next = new ListNode(1);
  38.                 p.print(p.partition(head, 0));

  39.         }
  40.         private void print(ListNode head) {
  41.                 // TODO Auto-generated method stub
  42.                 while (head!=null) {
  43.                         System.out.print(head.val+" ");
  44.                         head = head.next;
  45.                 }
  46.         }

  47. }
复制代码
回复

使用道具 举报

🔗
 楼主| jaly50 2014-12-22 10:01:48 | 只看该作者
全局:
  1. import java.util.Arrays;
  2. /*
  3. * Date:12/21/2014 Sun 5:59 PM
  4. * @author: Scarlett Chen
  5. */

  6. public class SurroundedRegion {
  7.             boolean [] hasEdge;
  8.             int[] union;
  9.             /*
  10.              * 一开始用了recursive dfs, 还发生了stackoverflow.QAQ .
  11.              * 最后用了algorithm1的unionfind写的~!感觉自己代码实现能力有提高呢!.
  12.              */
  13.             public void solve(char[][] board) {
  14.              int n = board.length;
  15.              if (n<1) return;
  16.              int m = board[0].length;
  17.              hasEdge = new boolean[n*m];
  18.              union = new int[n*m];
  19.              int pos;
  20.              for (int i=0; i<n; i++) {
  21.                      for (int j=0; j<m; j++) {
  22.                             pos = i*m +j;
  23.                             hasEdge[pos] = (i==0 ||j==0||i==n-1||j==m-1) ? true : false;
  24.                             union[pos] = pos;
  25.                             if (i>0 && board[i][j]== board[i-1][j]) {
  26.                                     union(pos, pos-m);
  27.                             }
  28.                             if (j>0 && board[i][j] == board[i][j-1]) {
  29.                                     union(pos, pos-1);
  30.                             }
  31.                       
  32.                      }
  33.              }
  34.              for (int i=0; i<n; i++) {
  35.                      for (int j=0; j<m; j++) {
  36.                              pos = i*m+j;
  37.                              if (board[i][j]=='O' &&  !hasEdge[findRoot(pos)]) {
  38.                                      board[i][j] = 'X';
  39.                              }
  40.                      }
  41.              }
  42.              for (int i=0; i<board.length; i++)
  43.                                 System.out.println(Arrays.toString(board[i]));
  44.              
  45.             }
  46.             
  47.             private void union(int x, int y) {
  48.                         int rootX = findRoot(x);
  49.                         int rootY = findRoot(y);
  50.                         union[rootX] = rootY;
  51.                         boolean hasedge = hasEdge[rootX] || hasEdge[rootY];
  52.                         hasEdge[rootY] = hasedge;
  53.        
  54.                 }

  55.                 private int findRoot(int x) {
  56.                         if (union[x]==x) return x;
  57.                         else return findRoot(union[x]);
  58.                 }


  59.         public static void main(String[] args) {
  60.                 // TODO Auto-generated method stub
  61.                 SurroundedRegion sr = new SurroundedRegion();
  62.                 char[][] board = new char[][] {{'X', 'X', 'X', 'X'},
  63.                                                                                 {'X', 'O', 'O', 'X'},
  64.                                                                                 {'X', 'X', 'O', 'X'},
  65.                                                                                 {'X', 'O' ,'X' ,'X'}};
  66.                 sr.solve(board);
  67.         }
  68.        
  69.        
  70.         //Failed
  71.         //Limitation in recursion depth
  72.         //sometimes we need to use stack to do bfs or dfs.
  73.          boolean[][] withEdge;
  74.             char[][] board;
  75.             int n;
  76.             int m;
  77.         public void solve_fail(char[][] board) {
  78.                n= board.length;
  79.                this. board = board;
  80.                if (n<1) return;
  81.                m = board[0].length;
  82.                withEdge = new boolean[n][m];
  83.                for (int i=0; i<n; i++) {
  84.                    Arrays.fill(withEdge[i], false);
  85.                }
  86.                 for (int i=0; i<n; i++) {
  87.                  if (board[i][0]=='O') {
  88.                      if (!withEdge[i][0]) {
  89.                          dfs(i,0);
  90.                      }
  91.                  }
  92.                 if (board[i][m-1]=='O') {
  93.                      if (!withEdge[i][m-1]) {
  94.                          dfs(i,m-1);
  95.                      }
  96.                  }
  97.                 }
  98.                for (int j=0; j<m; j++) {
  99.                    if (board[0][j]=='O') {
  100.                        if (!withEdge[0][j]) {
  101.                          dfs(0,j);
  102.                        }
  103.                    }
  104.                   if (board[n-1][j]=='O') {
  105.                        if (!withEdge[n-1][j]) {
  106.                          dfs(n-1,j);
  107.                        }
  108.                    }
  109.                }
  110.               for (int i=0; i<n; i++) {
  111.                   for (int j=0; j<board[0].length; j++) {
  112.                       if (board[i][j]=='O' && !withEdge[i][j]) {
  113.                           board[i][j] = 'X';
  114.                       }
  115.                   }
  116.               }
  117.                 
  118.             }
  119.             public void dfs(int row, int col) {
  120.                     withEdge[row][col] = true;
  121.                 if (row>0 && board[row-1][col]=='O' && !withEdge[row-1][col]) {
  122.                     dfs(row-1, col);
  123.                 }
  124.                 if (row<n-1 && board[row+1][col]=='O' && !withEdge[row+1][col]) {
  125.                     dfs(row+1, col);
  126.                 }
  127.                 if (col>0 && board[row][col-1]=='O' && !withEdge[row][col-1]) {
  128.                     dfs(row, col-1);
  129.                 }
  130.                 if (col<board[0].length-1 && board[row][col+1]=='O' && !withEdge[row][col+1]) {
  131.                     dfs(row, col+1);
  132.                 }
  133.             }
  134.        
  135. }
复制代码
回复

使用道具 举报

🔗
 楼主| jaly50 2014-12-22 11:08:28 | 只看该作者
全局:
  1. import java.util.HashMap;
  2. import java.util.Map;
  3. import java.util.Stack;
  4. /*
  5. * LeetCode: 148 Clone Graph
  6. * @author:Scarlett Chen
  7. * @date: 12/21/2014 Sun 7:04 PM
  8. * clone一个无向图,用栈一个一个访问结点,用hashmap记录clone的结点
  9. * 最近写代码都是一次过,真是不好意思嘿嘿嘿~~ 不过还是用了ide,如果没有提示的话,常常记不得如stack or map 的method的name
  10. */

  11. public class CloneGraph {
  12.          public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
  13.                 //To traverse the original nodes
  14.                 Stack<UndirectedGraphNode> stack = new Stack<UndirectedGraphNode>();
  15.                 //To record lable and its cloned Graph
  16.                 Map<Integer,UndirectedGraphNode> clone = new HashMap<Integer,UndirectedGraphNode>();
  17.                 if (node==null) return node;
  18.                 stack.push(node);
  19.                 clone.put(node.label, new UndirectedGraphNode(node.label));
  20.                 while (!stack.isEmpty()) {
  21.                    UndirectedGraphNode root = stack.pop();
  22.                    UndirectedGraphNode cloneRoot = clone.get(root.label);
  23.                    for (UndirectedGraphNode nei:root.neighbors) {
  24.                            UndirectedGraphNode cloneNei;
  25.                           
  26.                            //说明该结点已加入栈中
  27.                            if (clone.containsKey(nei.label)) {
  28.                                    cloneNei = clone.get(nei.label);
  29.                                   
  30.                            }
  31.                            else {
  32.                                    cloneNei = new UndirectedGraphNode(nei.label);
  33.                                    clone.put(nei.label, cloneNei);
  34.                                    stack.push(nei);
  35.                            }
  36.                            cloneRoot.neighbors.add(cloneNei);
  37.                       
  38.                    }
  39.                    
  40.                 
  41.                 }
  42.                 return clone.get(node.label);
  43.                  
  44.          }
  45.         public static void main(String[] args) {
  46.                 // TODO Auto-generated method stub

  47.         }

  48. }
复制代码
回复

使用道具 举报

🔗
 楼主| jaly50 2014-12-24 16:46:19 | 只看该作者
全局:
  1. /*
  2. * LeetCode 149  Recover Binary Search Tree
  3. * @author: Scarlett Chen
  4. * @date: 12/24/2014 Wed 12:43 AM
  5. * 这道题告诉我们 要巧用全局变量!
  6. * 以及理解一下~两个互相交换的node,在dfs中,第一个一定是和它下一个对比才被发现错的!第二个和它上一个对比发现错的!---利用这个规律就很好写了!
  7. */
  8. public class RecoverBST {
  9.             TreeNode prev;
  10.             TreeNode first;
  11.             TreeNode second;
  12.             public void recoverTree(TreeNode root) {
  13.                first = null;
  14.                second = null;
  15.                 prev = new TreeNode(Integer.MIN_VALUE);
  16.                 if (root==null) return;
  17.                 dfs(root);
  18.                 if (first!=null && second!=null)
  19.                         swap(first,second);
  20.             }
  21.             private void dfs(TreeNode root) {
  22.                 if (root.left!=null)  dfs(root.left);
  23.                 if (prev.val > root.val) {
  24.                     if (first == null)
  25.                             first = prev;
  26.                     second = root;
  27.                 }

  28.                 prev = root;
  29.                if (root.right!=null) dfs(root.right);
  30.             }
  31.             public void swap(TreeNode first, TreeNode second) {
  32.                int temp = first.val;
  33.                first.val = second.val;
  34.                second.val = temp;
  35.             }
  36.         public static void main(String[] args) {
  37.                 // TODO Auto-generated method stub
  38.        TreeNode head = new TreeNode(0);
  39.        TreeNode b = new TreeNode(1);
  40.        head.left = b;
  41.        RecoverBST rb = new RecoverBST();
  42.        rb.recoverTree(head);
  43.         }

  44. }
复制代码
回复

使用道具 举报

🔗
 楼主| jaly50 2014-12-25 04:52:37 | 只看该作者
全局:
  1. import java.util.Arrays;
  2. /*
  3. * LeetCode 152 Interleaving String
  4. * DP o(n^2)
  5. * @author: Scarlett.chen
  6. * @date:12/24/2014 Wed 12:50 PM
  7. * 注意边界值,len1==0等情况
  8. * 以及f[i][j]表示s1的前i个和s2的前j个,是不是能构成s3的前i+j个
  9. */

  10. public class InterLeaving {
  11.          public boolean isInterleave(String s1, String s2, String s3) {
  12.                  int len1 = s1.length();
  13.                  int len2 = s2.length();
  14.                  int len3 = s3.length();
  15.                  if (len3!=len2+len1) return false;
  16.                  if (len1==0) return s2.equals(s3);
  17.                  if (len2 == 0) return s1.equals(s3);
  18.                  boolean[][] f = new boolean[len1+1][len2+1];
  19.                  
  20.                  for (int i=0; i<=len1; i++) Arrays.fill(f[i], false);
  21.                  f[0][0] = true;
  22.                  for (int i=0; i<=len1; i++) {
  23.                          for (int j=0; j<=len2; j++) {
  24.                                  if (i>0 && s1.charAt(i-1) == s3.charAt(i-1+j)) {
  25.                                          f[i][j] = f[i-1][j] ||f[i][j];
  26.                                  }
  27.                                  if (j>0 && s2.charAt(j-1) == s3.charAt(i+j-1)) {
  28.                                          f[i][j] = f[i][j-1] ||f[i][j];
  29.                                  }
  30.                                  
  31.                          }
  32.                  }
  33.                  
  34.          return f[len1][len2];
  35.          }
  36.         public static void main(String[] args) {
  37.                 // TODO Auto-generated method stub
  38.                 InterLeaving il = new InterLeaving();
  39.                 System.out.println(il.isInterleave("ab", "aa", "abaa"));
  40.         }

  41. }
复制代码
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表