锘??xml version="1.0" encoding="utf-8" standalone="yes"?>蜜乳av一区二区三区,精品久久久国产,中文字幕一区二区三区四区五区六区http://www.aygfsteel.com/menglee/category/54046.html縐嬮縐嬮洦錛岀殕鍏ユ垜蹇?/description>zh-cnTue, 14 Jan 2014 22:53:39 GMTTue, 14 Jan 2014 22:53:39 GMT60[Leetcode] Trapping Rain Waterhttp://www.aygfsteel.com/menglee/archive/2014/01/14/408898.htmlMeng LeeMeng LeeTue, 14 Jan 2014 01:16:00 GMThttp://www.aygfsteel.com/menglee/archive/2014/01/14/408898.htmlhttp://www.aygfsteel.com/menglee/comments/408898.htmlhttp://www.aygfsteel.com/menglee/archive/2014/01/14/408898.html#Feedback0http://www.aygfsteel.com/menglee/comments/commentRss/408898.htmlhttp://www.aygfsteel.com/menglee/services/trackbacks/408898.html綆楁硶寰堢畝鍗曪紝鏍稿績鎬濇兂鏄細瀵規(guī)煇涓糀[i]鏉ヨ錛岃兘trapped鐨勬渶澶氱殑water鍙栧喅浜庡湪i涔嬪墠鏈楂樼殑鍊糽eftMostHeight[i]鍜屽湪i鍙寵竟鐨勬渶楂樼殑鍊紃ightMostHeight[i]銆傦紙鍧囦笉鍖呭惈鑷韓錛夈傚鏋渕in(left,right) > A[i]錛岄偅涔堝湪i榪欎釜浣嶇疆涓婅兘trapped鐨剋ater灝辨槸min(left,right) – A[i]銆?/div>
鏈変簡榪欎釜鎯蟲硶灝卞ソ鍔炰簡錛岀涓閬嶄粠宸﹀埌鍙寵綆楁暟緇刲eftMostHeight錛岀浜岄亶浠庡彸鍒板乏璁$畻rightMostHeight錛屽湪絎簩閬嶇殑鍚屾椂灝卞彲浠ヨ綆楀嚭i浣嶇疆鐨勭粨鏋滀簡錛岃屼笖騫朵笉闇瑕佸紑絀洪棿鏉ュ瓨鏀緍ightMostHeight鏁扮粍銆?/div>
鏃墮棿澶嶆潅搴︽槸O(n)錛屽彧鎵簡涓ら亶銆?br />
 1 public class TrappingRainWater {
 2     public int trap(int A[], int n) {
 3         if (n <= 2)
 4             return 0;
 5 
 6         int[] lmh = new int[n];
 7         lmh[0] = 0;
 8         int maxh = A[0];
 9         for (int i = 1; i < n; ++i) {
10             lmh[i] = maxh;
11             if (maxh < A[i])
12                 maxh = A[i];
13         }
14         int trapped = 0;
15         maxh = A[n - 1];
16         for (int i = n - 2; i > 0; --i) {
17             int left = lmh[i];
18             int right = maxh;
19             int container = Math.min(left, right);
20             if (container > A[i]) {
21                 trapped += container - A[i];
22             }
23             if (maxh < A[i])
24                 maxh = A[i];
25         }
26         return trapped;
27     }
28 }


Meng Lee 2014-01-14 09:16 鍙戣〃璇勮
]]>[Leetcode] Permutation Sequencehttp://www.aygfsteel.com/menglee/archive/2014/01/07/408642.htmlMeng LeeMeng LeeTue, 07 Jan 2014 08:06:00 GMThttp://www.aygfsteel.com/menglee/archive/2014/01/07/408642.htmlhttp://www.aygfsteel.com/menglee/comments/408642.htmlhttp://www.aygfsteel.com/menglee/archive/2014/01/07/408642.html#Feedback0http://www.aygfsteel.com/menglee/comments/commentRss/408642.htmlhttp://www.aygfsteel.com/menglee/services/trackbacks/408642.htmlThe set [1,2,3,…,n] contains a total of n! unique permutations.
By listing and labeling all of the permutations in order,
We get the following sequence (ie, for n = 3):
"123"
"132"
"213"
"231"
"312"
"321"
Given n and k, return the kth permutation sequence.
Note: Given n will be between 1 and 9 inclusive.

榪欓亾棰樺叾瀹炴湁寰堝己鐨勮寰嬪彲寰傞鍏堬紝n涓厓绱犵殑鎺掑垪鎬繪暟鏄痭!銆傚湪涓嬮潰鐨勫垎鏋愪腑錛岃k鐨勮寖鍥存槸0 <= k < n!銆傦紙棰樼洰浠g爜瀹為檯涓婃槸1<=k<=n!)
鍙互鐪嬪埌涓涓寰嬶紝灝辨槸榪檔錛佷釜鎺掑垪涓紝絎竴浣嶇殑鍏冪礌鎬繪槸(n-1)!涓緇勫嚭鐜扮殑錛屼篃灝辮濡傛灉p = k / (n-1)!錛岄偅涔堟帓鍒楃殑鏈寮濮嬩竴涓厓绱犱竴瀹氭槸arr[p]銆?/div>
榪欎釜瑙勫緥鍙互綾繪帹涓嬪幓錛屽湪鍓╀綑鐨刵-1涓厓绱犱腑閫愭笎鎸戦夊嚭絎簩涓紝絎笁涓紝...錛屽埌絎琻涓厓绱犮傜▼搴忓氨緇撴潫銆?/div>
 1 /**
 2  * The set [1,2,3,…,n] contains a total of n! unique permutations.
 3  * 
 4  * By listing and labeling all of the permutations in order, We get the
 5  * following sequence (ie, for n = 3):
 6  * 
 7  * "123" "132" "213" "231" "312" "321" Given n and k, return the kth permutation
 8  * sequence.
 9  * 
10  * Note: Given n will be between 1 and 9 inclusive.
11  * 
12  */
13 
14 public class PermutationSequence {
15     public String getPermutation(int n, int k) {
16         char[] arr = new char[n];
17         int pro = 1;
18         for (int i = 0; i < n; ++i) {
19             arr[i] = (char) ('1' + i);
20             pro *= (i + 1);
21         }
22         k = k - 1;
23         k %= pro;
24         pro /= n;
25         for (int i = 0; i < n - 1; ++i) {
26             int selectI = k / pro;
27             k = k % pro;
28             pro /= (n - i - 1);
29             int temp = arr[selectI + i];
30             for (int j = selectI; j > 0; --j) {
31                 arr[i + j] = arr[i + j - 1];
32             }
33             arr[i] = (char) temp;
34         }
35         return String.valueOf(arr);
36     }
37 }
38 


Meng Lee 2014-01-07 16:06 鍙戣〃璇勮
]]>[Leetcode] Lowest Common Ancestor of a Binary Search Tree (BST) && Lowest Common Ancestor of Binary Treehttp://www.aygfsteel.com/menglee/archive/2014/01/06/408544.htmlMeng LeeMeng LeeMon, 06 Jan 2014 01:32:00 GMThttp://www.aygfsteel.com/menglee/archive/2014/01/06/408544.htmlhttp://www.aygfsteel.com/menglee/comments/408544.htmlhttp://www.aygfsteel.com/menglee/archive/2014/01/06/408544.html#Feedback0http://www.aygfsteel.com/menglee/comments/commentRss/408544.htmlhttp://www.aygfsteel.com/menglee/services/trackbacks/408544.html
Lowest Common Ancestor of a Binary Search Tree (BST)
Given a binary search tree (BST), find the lowest common ancestor of two given nodes in the BST.
       _______6______
      /              \
   ___2__          ___8__
  /      \        /      \
  0      _4       7       9
        /  \
        3   5
Using the above tree as an example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. 
But how about LCA of nodes 2 and 4? Should it be 6 or 2?
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between 
two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a 
node to be a descendant of itself).” Since a node can be a descendant of itself, the LCA of 2 and 
4 should be 2, according to this definition.
Hint:
A top-down walk from the root of the tree is enough.

 1 public class LowestCommonAncestorOfaBinarySearchTree {
 2     public TreeNode LCA(TreeNode root, TreeNode p, TreeNode q) {
 3         if (root == null || p == null || q == null)
 4             return null;
 5         if (Math.max(p.val, q.val) < root.val)
 6             return LCA(root.left, p, q);
 7         if (Math.min(p.val, q.val) > root.val)
 8             return LCA(root.right, p, q);
 9         return root;
10     }
11 }


Given a binary tree, find the lowest common ancestor of two given nodes in the tree.
 
 
        _______3______
       /              \
    ___5__          ___1__
   /      \        /      \
  6      _2       0       8
         /  \
         7   4
If you are not so sure about the definition of lowest common ancestor (LCA), please refer to my previous 
post: Lowest Common Ancestor of a Binary Search Tree (BST) or the definition of LCA here. Using the tree 
above as an example, the LCA of nodes 5 and 1 is 3. Please note that LCA for nodes 5 and 4 is 5.
 
Hint:
Top-down or bottom-up? Consider both approaches and see which one is more efficient.
 1 public class LowestCommonAncestorOfBinaryTree {
 2     public TreeNode LCA(TreeNode root, TreeNode p, TreeNode q) {
 3         if (root == null)
 4             return null;
 5         if (root == p || root == q)
 6             return root;
 7         TreeNode left = LCA(root.left, p, q);
 8         TreeNode right = LCA(root.right, p, q);
 9         if (left != null && right != null)
10             return root;
11         return left != null ? left : right;
12     }
13 }


Meng Lee 2014-01-06 09:32 鍙戣〃璇勮
]]>[Leetcode] Scramble Stringhttp://www.aygfsteel.com/menglee/archive/2014/01/05/408521.htmlMeng LeeMeng LeeSun, 05 Jan 2014 04:33:00 GMThttp://www.aygfsteel.com/menglee/archive/2014/01/05/408521.htmlhttp://www.aygfsteel.com/menglee/comments/408521.htmlhttp://www.aygfsteel.com/menglee/archive/2014/01/05/408521.html#Feedback0http://www.aygfsteel.com/menglee/comments/commentRss/408521.htmlhttp://www.aygfsteel.com/menglee/services/trackbacks/408521.htmlGiven 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.

 1 public class ScrambleString {
 2     public boolean isScramble(String s1, String s2) {
 3         if (s1.length() != s2.length())
 4             return false;
 5         if (s1.equals(s2))
 6             return true;
 7 
 8         int[] A = new int[26];
 9         for (int i = 0; i < s1.length(); i++) {
10             ++A[s1.charAt(i) - 'a'];
11         }
12 
13         for (int j = 0; j < s2.length(); j++) {
14             --A[s2.charAt(j) - 'a'];
15         }
16 
17         for (int k = 0; k < 26; k++) {
18             if (A[k] != 0)
19                 return false;
20         }
21 
22         for (int i = 1; i < s1.length(); i++) {
23             boolean result = isScramble(s1.substring(0, i), s2.substring(0, i))
24                     && isScramble(s1.substring(i), s2.substring(i));
25             result = result
26                     || (isScramble(s1.substring(0, i),
27                             s2.substring(s2.length() - i, s2.length())) && isScramble(
28                             s1.substring(i), s2.substring(0, s2.length() - i)));
29             if (result)
30                 return true;
31         }
32         return false;
33     }
34 }


Meng Lee 2014-01-05 12:33 鍙戣〃璇勮
]]>
[Leetcode] Largest Rectangle in Histogramhttp://www.aygfsteel.com/menglee/archive/2014/01/05/408520.htmlMeng LeeMeng LeeSun, 05 Jan 2014 04:31:00 GMThttp://www.aygfsteel.com/menglee/archive/2014/01/05/408520.htmlhttp://www.aygfsteel.com/menglee/comments/408520.htmlhttp://www.aygfsteel.com/menglee/archive/2014/01/05/408520.html#Feedback0http://www.aygfsteel.com/menglee/comments/commentRss/408520.htmlhttp://www.aygfsteel.com/menglee/services/trackbacks/408520.htmlGiven n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.
Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].
The largest rectangle is shown in the shaded area, which has area = 10 unit.
For example,
Given height = [2,1,5,6,2,3],
return 10.

鏈闇瑕佷嬌鐢ㄦ爤緇存姢涓涓珮搴﹀崟璋冮掑鐨勫簭鍒椾笅鏍囷紝濡傛灉閬囧埌涓涓厓绱犳瘮褰撳墠鏍堥《鍏冪礌楂樺害灝忥紝閭d箞鍑烘爤錛屽茍璁$畻褰撳墠鏈澶ч潰縐傚鏋滄爤涓虹┖錛岄渶瑕佺壒孌婅冭檻銆?br />
 1 public class LargestRectangleinHistogram {
 2     public int largestRectangleArea(int[] height) {
 3         Stack<Integer> stack = new Stack<Integer>();
 4         int i = 0;
 5         int maxArea = 0;
 6         int[] h = new int[height.length + 1];
 7         h = Arrays.copyOf(height, height.length + 1);
 8         while (i < h.length) {
 9             if (stack.isEmpty() || h[stack.peek()] <= h[i]) {
10                 stack.push(i++);
11             } else {
12                 int t = stack.pop();
13                 maxArea = Math.max(maxArea, h[t] * (stack.isEmpty() ? i : i - stack.peek() - 1));
14             }
15         }
16         return maxArea;
17     }
18 }


Meng Lee 2014-01-05 12:31 鍙戣〃璇勮
]]>
[Leetcode] Binary Tree Inorder Traversalhttp://www.aygfsteel.com/menglee/archive/2014/01/04/408477.htmlMeng LeeMeng LeeSat, 04 Jan 2014 03:17:00 GMThttp://www.aygfsteel.com/menglee/archive/2014/01/04/408477.htmlhttp://www.aygfsteel.com/menglee/comments/408477.htmlhttp://www.aygfsteel.com/menglee/archive/2014/01/04/408477.html#Feedback0http://www.aygfsteel.com/menglee/comments/commentRss/408477.htmlhttp://www.aygfsteel.com/menglee/services/trackbacks/408477.htmlGiven a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3},
   1
    \
     2
    /
   3
return [1,3,2].
Note: Recursive solution is trivial, could you do it iteratively?

鍒囪p鑺傜偣鍒濆鏃舵寚鍚憆oot.left銆備唬鐮佸涓嬶細
 1 public class BinaryTreeInorderTraversal {
 2     public ArrayList<Integer> inorderTraversal(TreeNode root) {
 3         ArrayList<Integer> inOrder = new ArrayList<Integer>();
 4         if (root == null)
 5             return inOrder;
 6         Stack<TreeNode> s = new Stack<TreeNode>();
 7         s.add(root);
 8         TreeNode p = root.left;
 9         while (!s.empty()) {
10             while (p != null) {
11                 s.add(p);
12                 p = p.left;
13             }
14             TreeNode n = s.pop();
15             inOrder.add(n.val);
16             p = n.right;
17             if (p != null) {
18                 s.add(p);
19                 p = p.left;
20             }
21         }
22         return inOrder;
23     }
24 }


Meng Lee 2014-01-04 11:17 鍙戣〃璇勮
]]>
[Leetcode] Subsets IIhttp://www.aygfsteel.com/menglee/archive/2014/01/03/408444.htmlMeng LeeMeng LeeFri, 03 Jan 2014 08:40:00 GMThttp://www.aygfsteel.com/menglee/archive/2014/01/03/408444.htmlhttp://www.aygfsteel.com/menglee/comments/408444.htmlhttp://www.aygfsteel.com/menglee/archive/2014/01/03/408444.html#Feedback0http://www.aygfsteel.com/menglee/comments/commentRss/408444.htmlhttp://www.aygfsteel.com/menglee/services/trackbacks/408444.htmlGiven a collection of integers that might contain duplicates, S, return all possible subsets.
Note:
Elements in a subset must be in non-descending order.
The solution set must not contain duplicate subsets.
For example,
If S = [1,2,2], a solution is:
[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]

鐢變簬鍏冪礌涓彲鑳藉瓨鍦ㄩ噸澶嶏紝鍥犳杈冧箣浜嶴ubset鐨勫疄鐜幫紝闇瑕佸姞涓浜涘垽鏂傚鏋滅鍒頒簡閲嶅鍏冪礌錛屽彧闇瑕佸湪涓婁竴嬈¤凱浠f柊澧炵殑瀛愰泦鐨勫熀紜涓婂啀榪涜榪唬鍗沖彲銆傚疄鐜頒唬鐮佸涓嬶細
 1 public class SubsetsII {
 2     public ArrayList<ArrayList<Integer>> subsetsWithDup(int[] num) {
 3         ArrayList<ArrayList<Integer>> ret = new ArrayList<ArrayList<Integer>>();
 4         ArrayList<ArrayList<Integer>> lastLevel = null;
 5         ret.add(new ArrayList<Integer>());
 6         Arrays.sort(num);
 7         for (int i = 0; i < num.length; i++) {
 8             ArrayList<ArrayList<Integer>> tmp = new ArrayList<ArrayList<Integer>>();
 9             ArrayList<ArrayList<Integer>> prev = i == 0 || num[i] != num[i - 1] ? ret : lastLevel;
10             for (ArrayList<Integer> s : prev) {
11                 ArrayList<Integer> newSet = new ArrayList<Integer>(s);
12                 newSet.add(num[i]);
13                 tmp.add(newSet);
14             }
15             ret.addAll(tmp);
16             lastLevel = tmp;
17         }
18         return ret;
19     }
20 }


Meng Lee 2014-01-03 16:40 鍙戣〃璇勮
]]>
[Leetcode] Word Ladder IIhttp://www.aygfsteel.com/menglee/archive/2014/01/02/408381.htmlMeng LeeMeng LeeThu, 02 Jan 2014 05:59:00 GMThttp://www.aygfsteel.com/menglee/archive/2014/01/02/408381.htmlhttp://www.aygfsteel.com/menglee/comments/408381.htmlhttp://www.aygfsteel.com/menglee/archive/2014/01/02/408381.html#Feedback0http://www.aygfsteel.com/menglee/comments/commentRss/408381.htmlhttp://www.aygfsteel.com/menglee/services/trackbacks/408381.htmlGiven two words (start and end), and a dictionary, find all shortest transformation sequence(s) from start to end, such that:
Only one letter can be changed at a time
Each intermediate word must exist in the dictionary
For example,
Given:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]
Return
  [
    ["hit","hot","dot","dog","cog"],
    ["hit","hot","lot","log","cog"]
  ]
Note:
All words have the same length.
All words contain only lowercase alphabetic characters.

榪欎釜棰樼洰搴旇綆楁槸leetcode涓婃瘮杈冮毦鐨勯鐩簡銆傚垰寮濮嬫垜閲囩敤浜嗗拰Word Ladder鐩鎬技鐨勫仛娉曪紝鍙槸鐢ˋrrayList璁板綍浜嗗綋鍓嶅彉鎹㈣礬寰勶紝鍦ㄥ皬鏁版嵁鐨勬儏鍐典笅鍙互Accept錛屼絾鏄ぇ鏁版嵁瓚呮椂銆傜┒鍏跺師鍥狅紝鏄敱浜庝負姣忎釜褰撳墠鑺傜偣璁板綍鍙樻崲璺緞鐨勬椂鍊欙紝闇瑕佸鍒朵箣鍓嶇殑ArrayList錛岃繖涓椂闂村紑閿杈冨ぇ銆?br />鍏跺疄錛屾垜浠彲浠ラ噰鐢ㄤ竴涓狹ap<String, HashSet<String>>緇撴瀯錛岃褰曞瓧鍏稿崟璇嶇殑姣忎竴涓墠椹憋紝榪欐牱鎴戜滑鍙互浠巈nd鍙嶅悜閬嶅巻錛屾瀯閫犲嚭杞崲璺緞銆?br />鍚屾椂錛屾垜鍒╃敤浜嗕袱涓狝rrayList錛屼氦鏇胯褰曚笂涓灞傚拰涓嬩竴灞傜殑鑺傜偣錛屽鏋滀笅涓灞傝妭鐐逛負絀猴紝鍒欎笉瀛樺湪璺緞錛岀珛鍗寵繑鍥炪傚鏋滀笅涓灞備腑鍑虹幇浜唀nd錛岃瘉鏄庢壘鍒頒簡鎵鏈夌殑鏈鐭礬寰勶紝鍋滄鎼滅儲寮濮嬫瀯閫犺礬寰勩傚疄鐜頒唬鐮佸涓嬶細
 1 public class WordLadderII {
 2     private void GeneratePath(Map<String, ArrayList<String>> prevMap,
 3             ArrayList<String> path, String word,
 4             ArrayList<ArrayList<String>> ret) {
 5         if (prevMap.get(word).size() == 0) {
 6             path.add(0, word);
 7             ArrayList<String> curPath = new ArrayList<String>(path);
 8             ret.add(curPath);
 9             path.remove(0);
10             return;
11         }
12 
13         path.add(0, word);
14         for (String pt : prevMap.get(word)) {
15             GeneratePath(prevMap, path, pt, ret);
16         }
17         path.remove(0);
18     }
19 
20     public ArrayList<ArrayList<String>> findLadders(String start, String end,
21             HashSet<String> dict) {
22         ArrayList<ArrayList<String>> ret = new ArrayList<ArrayList<String>>();
23         Map<String, ArrayList<String>> prevMap = new HashMap<String, ArrayList<String>>();
24         dict.add(start);
25         dict.add(end);
26         for (String d : dict) {
27             prevMap.put(d, new ArrayList<String>());
28         }
29         ArrayList<HashSet<String>> candidates = new ArrayList<HashSet<String>>();
30         candidates.add(new HashSet<String>());
31         candidates.add(new HashSet<String>());
32         int current = 0;
33         int previous = 1;
34         candidates.get(current).add(start);
35         while (true) {
36             current = current == 0 ? 1 : 0;
37             previous = previous == 0 ? 1 : 0;
38             for (String d : candidates.get(previous)) {
39                 dict.remove(d);
40             }
41             candidates.get(current).clear();
42             for (String wd : candidates.get(previous)) {
43                 for (int pos = 0; pos < wd.length(); ++pos) {
44                     StringBuffer word = new StringBuffer(wd);
45                     for (int i = 'a'; i <= 'z'; ++i) {
46                         if (wd.charAt(pos) == i) {
47                             continue;
48                         }
49 
50                         word.setCharAt(pos, (char) i);
51 
52                         if (dict.contains(word.toString())) {
53                             prevMap.get(word.toString()).add(wd);
54                             candidates.get(current).add(word.toString());
55                         }
56                     }
57                 }
58             }
59 
60             if (candidates.get(current).size() == 0) {
61                 return ret;
62             }
63             if (candidates.get(current).contains(end)) {
64                 break;
65             }
66         }
67 
68         ArrayList<String> path = new ArrayList<String>();
69         GeneratePath(prevMap, path, end, ret);
70 
71         return ret;
72     }
73 }


Meng Lee 2014-01-02 13:59 鍙戣〃璇勮
]]>
[Leetcode] Distinct Subsequences && Edit Distancehttp://www.aygfsteel.com/menglee/archive/2013/12/31/408231.htmlMeng LeeMeng LeeTue, 31 Dec 2013 02:21:00 GMThttp://www.aygfsteel.com/menglee/archive/2013/12/31/408231.htmlhttp://www.aygfsteel.com/menglee/comments/408231.htmlhttp://www.aygfsteel.com/menglee/archive/2013/12/31/408231.html#Feedback0http://www.aygfsteel.com/menglee/comments/commentRss/408231.htmlhttp://www.aygfsteel.com/menglee/services/trackbacks/408231.htmlDistinct Subsequences

Given a string S and a string T, count the number of distinct sub sequences of T in S.
A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE" is a subsequence of "ABCDE" while "AEC" is not).
Here is an example:
S = "rabbbit", T = "rabbit"
Return 3.

榪欎袱涓鐩緢鐩鎬技錛岀姸鎬佹柟紼嬫槸f(i, j) = f(i - 1, j) + S[i] == T[j]? f(i - 1, j - 1) : 0 Where f(i, j) is the number of distinct sub-sequence for T[0:j] in S[0:i].
鏁扮粍鍒濆鎯呭喌鏄涓鍒楀叏閮ㄦ槸1錛屼唬琛═瀛楃涓叉槸絀轟覆錛孲鍜岃嚜宸卞仛鍖歸厤銆傚疄鐜頒唬鐮佸涓嬶細
 1 public class DistinctSubsequences {
 2     public int numDistinct(String S, String T) {
 3         int[][] f = new int[S.length() + 1][T.length() + 1];
 4         for (int k = 0; k < S.length(); k++)
 5             f[k][0] = 1;
 6         for (int i = 1; i <= S.length(); i++) {
 7             for (int j = 1; j <= T.length(); j++) {
 8                 if (S.charAt(i - 1) == T.charAt(j - 1)) {
 9                     f[i][j] += f[i - 1][j] + f[i - 1][j - 1];
10                 } else {
11                     f[i][j] += f[i - 1][j];
12                 }
13             }
14         }
15         return f[S.length()][T.length()];
16     }
17 }

Edit Distance
Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)
You have the following 3 operations permitted on a word:
a) Insert a character
b) Delete a character
c) Replace a character

 1 public class EditDistance {
 2     public int minDistance(String word1, String word2) {
 3         if (word1.length() == 0 || word2.length() == 0)
 4             return word1.length() == 0 ? word2.length() : word1.length();
 5         int[][] arr = new int[word2.length() + 1][word1.length() + 1];
 6         for (int i = 0; i <= word1.length(); i++) {
 7             arr[0][i] = i;
 8         }
 9         for (int j = 0; j <= word2.length(); j++) {
10             arr[j][0] = j;
11         }
12         for (int i = 0; i < word1.length(); i++) {
13             for (int j = 0; j < word2.length(); j++) {
14                 if (word1.charAt(i) == word2.charAt(j)) {
15                     arr[j + 1][i + 1] = arr[j][i];
16                 } else {
17                     int dis = Math.min(arr[j][i + 1], arr[j + 1][i]);
18                     arr[j + 1][i + 1] = Math.min(arr[j][i], dis) + 1;
19                 }
20             }
21         }
22         return arr[word2.length()][word1.length()];
23     }
24 }


Meng Lee 2013-12-31 10:21 鍙戣〃璇勮
]]>
[Leetcode] 鍚堝茍鍖洪棿http://www.aygfsteel.com/menglee/archive/2013/12/26/408066.htmlMeng LeeMeng LeeThu, 26 Dec 2013 06:47:00 GMThttp://www.aygfsteel.com/menglee/archive/2013/12/26/408066.htmlhttp://www.aygfsteel.com/menglee/comments/408066.htmlhttp://www.aygfsteel.com/menglee/archive/2013/12/26/408066.html#Feedback0http://www.aygfsteel.com/menglee/comments/commentRss/408066.htmlhttp://www.aygfsteel.com/menglee/services/trackbacks/408066.html1銆佺粰瀹氫竴緇勫尯闂達紝琛ㄧず涓篬start,end]錛岃緇欏嚭鏂規(guī)硶錛屽皢鏈夐噸鍙犵殑鍖洪棿榪涜鍚堝茍銆備緥濡傦細
緇欏畾錛歔1,3],[2,6],[8,10],[15,18],
鍚堝茍錛歔1,6],[8,10],[15,18].
鍒嗘瀽錛氶鐩緢鐩磋錛岄鍏堟妸鍖洪棿閫掑鎺掑簭錛岀劧鍚庝粠澶村悎騫訛紝鍚堝茍鏃惰瀵熷綋鍓嶅尯闂寸殑start鏄惁灝忎簬鎴栫瓑浜庡墠涓涓尯闂寸殑end銆備唬鐮佸涓嬶細
 1 public class MergeIntervals {
 2     public class IntervalCmp implements Comparator<Interval> {
 3         @Override
 4         public int compare(Interval i1, Interval i2) {
 5             if (i1.start < i2.start) return -1;
 6             if (i1.start == i2.start && i1.end <= i2.end) return -1;
 7             return 1;
 8         }
 9     }
10     
11     public ArrayList<Interval> merge(ArrayList<Interval> intervals) {
12         ArrayList<Interval> ret = new ArrayList<Interval>();
13         if (intervals.size() == 0) return ret;
14         Interval[] arr = new Interval[intervals.size()];
15         intervals.toArray(arr);
16         Arrays.sort(arr, new IntervalCmp());
17         int start = arr[0].start;
18         int end = arr[0].end;
19         for (int i = 0; i < arr.length; i++) {
20             if (arr[i].start <= end) {
21                 end = Math.max(end, arr[i].end);
22             } else {
23                 ret.add(new Interval(start, end));
24                 start = arr[i].start;
25                 end = arr[i].end;
26             }
27         }
28         ret.add(new Interval(start, end));
29         return ret;
30     }
31 }
2銆佺粰瀹氱殑涓緇勫尯闂達紝灝嗗尯闂翠腑鐨勫瓨鍦ㄧ殑浠繪剰鍖洪棿鐨勭埗鍖洪棿鍒犻櫎錛屼緥濡傦細
緇欏畾錛歔1,2] [1,3] [1,4] [5,9] [6,8]
鍒犻櫎鍚庯細[1,2] [6,8]
鍒嗘瀽錛氭棰樻毚鍔涚殑瑙f硶鐨勫鏉傚害涓篛(N^2)銆傚彈涓婁竴棰樻帓搴忕殑鍚彂錛屾槸鍚︽湁濂戒竴鐐圭殑鎬濊礬鍛紵
鎴戜滑鍙互鎸夌収start閫掑鎺掑簭錛岃嫢start鐩哥瓑錛屽垯鎸夌収end閫掑噺鎺掑簭銆傝冭檻鎺掑簭鍚庣殑絎琲-1 鍜岀i涓尯闂達紝鐢變簬start鏄掑鐨勶紝鎵浠ョi-1涓尯闂寸殑start鑲畾灝忎簬絳変簬絎琲涓尯闂寸殑start銆傝嫢絎琲-1涓尯闂寸殑end澶т簬絳変簬絎琲涓尯闂寸殑end錛屽垯絎琲-1涓尯闂村氨鎴愪負絎琲涓尯闂寸殑鐖跺尯闂翠簡銆?/div>

鎸夌収榪欎釜鎬濊礬錛屽彲浠ヨ瘯鐫鍦ㄦ帓搴忎箣鍚庨嗗悜欏哄簭澶勭悊姣忎竴涓尯闂淬傚亣璁懼綋鍓嶅鐞嗙i涓尯闂達紝濡傚墠鎵榪幫紝鑻ョi-1涓尯闂寸殑end澶т簬絳変簬絎琲涓尯闂寸殑end錛屽垯絎琲-1涓尯闂存垚涓虹i涓尯闂寸殑鐖跺尯闂達紝鍙互淇濈暀絎琲涓尯闂達紝灝嗙i-1涓尯闂村垹闄ゃ傜敱浜庣i-1涓尯闂存槸絎琲涓尯闂寸殑鐖跺尯闂達紝鎵浠ョi-1涓尯闂寸殑鐖跺尯闂翠篃鏄i涓尯闂寸殑鐖跺尯闂達紝榪欑鎯呭艦涓嬪垹鎺夌i-1涓尯闂達紝鍚庣畫涓嶄細婕忓垹絎琲-1涓尯闂寸殑鐖跺尯闂淬傝嫢絎琲-1涓尯闂寸殑end灝忎簬絎琲涓尯闂寸殑end錛屽垯鍙互璺寵繃絎琲涓尯闂達紝寮濮嬪鐞嗙i-1涓尯闂淬傚洜涓烘寜鐓ц繖縐嶅鐞嗙殑鏂規(guī)硶錛屽湪澶勭悊鍒扮i涓尯闂存椂錛岃鍖洪棿涓嶄細鏄換浣曞尯闂寸殑鐖跺尯闂達紙鑻ユ槸鐖跺尯闂村凡緇忚濡傚墠鎵榪扮殑鏂規(guī)硶鍒犻櫎浜嗭級銆傝屼笖錛屽湪榪欑鎯呭艦涓嬶紝鍚庣畫鍙兘鍑虹幇鐨勭i涓尯闂寸殑鐖跺尯闂翠細鏄i-1涓尯闂寸殑鐖跺尯闂達紝鎵浠ヤ篃涓嶄細婕忔帀絎琲涓尯闂寸殑鐖跺尯闂淬傛墍浠ユ帓搴忎箣鍚庨嗗悜澶勭悊錛屽彧闇瑕丱(N)鐨勬椂闂達紝灝卞彲浠ヨВ鍐寵繖閬撻棶棰樸傛暣浣撶殑鏃墮棿澶嶆潅搴︿負O(nlogn)銆?br />
 1 public class Solution {
 2     public class IntervalCmp implements Comparator<Interval> {
 3         @Override
 4         public int compare(Interval i1, Interval i2) {
 5             if (i1.start < i2.start) return -1;
 6             if (i1.start == i2.start && i1.end >= i2.end) return -1;
 7             return 1;
 8         }
 9     }
10     
11     public ArrayList<Interval> merge(ArrayList<Interval> intervals) {
12         ArrayList<Interval> ret = new ArrayList<Interval>();
13         if (intervals.size() == 0) return ret;
14         Interval[] arr = new Interval[intervals.size()];
15         intervals.toArray(arr);
16         Arrays.sort(arr, new IntervalCmp());
17         int start = arr[arr.length - 1].start;
18         int end = arr[arr.length - 1].end;
19         for (int i = arr.length - 2; i >= 0; i--) {
20             if (arr[i].end < end) {
21                 ret.add(new Interval(start, end));
22                 start = arr[i].start;
23                 end = arr[i].end;
24             }
25         }
26         ret.add(new Interval(start, end));
27         return ret;
28     }
29 }


Meng Lee 2013-12-26 14:47 鍙戣〃璇勮
]]>[Leetcode] Trianglehttp://www.aygfsteel.com/menglee/archive/2013/12/25/408006.htmlMeng LeeMeng LeeWed, 25 Dec 2013 03:31:00 GMThttp://www.aygfsteel.com/menglee/archive/2013/12/25/408006.htmlhttp://www.aygfsteel.com/menglee/comments/408006.htmlhttp://www.aygfsteel.com/menglee/archive/2013/12/25/408006.html#Feedback0http://www.aygfsteel.com/menglee/comments/commentRss/408006.htmlhttp://www.aygfsteel.com/menglee/services/trackbacks/408006.htmlGiven a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
For example, given the following triangle
[
     [2],
    [3,4],
   [6,5,7],
  [4,1,8,3]
]
The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).
Note:
Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle.

鏈鏈潵鐨勬兂娉曟槸鐢ㄩ掑綊鍋氾紝瀹炵幇浠g爜濡備笅錛?br />
 1 public class Solution {
 2     public int minimumTotal(ArrayList<ArrayList<Integer>> triangle) {
 3         int row = triangle.size();
 4         return findMinPath(triangle, 0, 0, row);
 5     }
 6 
 7     private int findMinPath(ArrayList<ArrayList<Integer>> triangle, int row,
 8             int col, int totalRow) {
 9         if (row == totalRow - 1) {
10             return triangle.get(row).get(col);
11         } else {
12             return triangle.get(row).get(col) + Math.min(findMinPath(triangle, row + 1, col, totalRow), findMinPath(triangle, row + 1, col + 1, totalRow));
13         }
14     }
15 }
鎻愪氦涔嬪悗鍙戠幇瓚呮椂錛屼簬鏄冭檻鍒板彲鑳芥槸閫掑綊鐨勫紑閿闂錛岃冭檻鐢ㄨ凱浠hВ棰樸傚疄鐜板涓嬶細
 1 public class Triangle {
 2     public int minimumTotal(ArrayList<ArrayList<Integer>> triangle) {
 3         int n = triangle.size() - 1;
 4         int[] path = new int[triangle.size()];
 5         for (int o = 0; o < triangle.get(n).size(); o++) {
 6             path[o] = triangle.get(n).get(o);
 7         }
 8         for (int i = triangle.size() - 2; i >= 0; i--) {
 9             for (int j = 0, t = 0; j < triangle.get(i + 1).size() - 1; j++, t++) {
10                 path[t] = triangle.get(i).get(t)
11                         + Math.min(path[j], path[j + 1]);
12             }
13         }
14         return path[0];
15     }
16 }
榪欎釜瑙f硶鐨勬牳蹇冩槸浠庡彾鑺傜偣鑷簳鍚戜笂鏋勯犺В絀洪棿銆?/div>

Meng Lee 2013-12-25 11:31 鍙戣〃璇勮
]]>[Leetcode] Gray Code && Subsetshttp://www.aygfsteel.com/menglee/archive/2013/12/24/407962.htmlMeng LeeMeng LeeTue, 24 Dec 2013 04:06:00 GMThttp://www.aygfsteel.com/menglee/archive/2013/12/24/407962.htmlhttp://www.aygfsteel.com/menglee/comments/407962.htmlhttp://www.aygfsteel.com/menglee/archive/2013/12/24/407962.html#Feedback0http://www.aygfsteel.com/menglee/comments/commentRss/407962.htmlhttp://www.aygfsteel.com/menglee/services/trackbacks/407962.htmlSubsets鐨勮В娉曟槸浠庣┖闆嗗紑濮嬶紝渚濇鍙栨瘡涓涓厓绱犱笌瀛愰泦涓殑姣忎釜闆嗗悎鍋氬茍鎿嶄綔銆傚疄鐜頒唬鐮佸涓嬶細

 1 public class Subsets {
 2     public ArrayList<ArrayList<Integer>> subsets(int[] S) {
 3         Arrays.sort(S);
 4         ArrayList<ArrayList<Integer>> subsets = new ArrayList<ArrayList<Integer>>();
 5         subsets.add(new ArrayList<Integer>());
 6         for (int i = 0; i < S.length; i++) {
 7             int size = subsets.size();
 8             for (int j = 0; j < size; j++) {
 9                 ArrayList<Integer> subset = new ArrayList<Integer>(
10                         subsets.get(j));
11                 subset.add(S[i]);
12                 subsets.add(subset);
13             }
14         }
15         return subsets;
16     }
17 }

Gray Code鐨勭畻娉曟槸鍒濆鏃墮泦鍚堜腑鍙湁{0, 1}涓や釜鍏冪礌錛屾鍚庡湪姣忎釜鍏冪礌鐨勫墠闈㈤檮鍔犱竴涓?銆傚疄鐜頒唬鐮佸涓嬶細

 1 public class GrayCode {
 2     public ArrayList<Integer> grayCode(int n) {
 3         ArrayList<Integer> result = new ArrayList<Integer>();
 4         if (n == 0) {
 5             result.add(0);
 6             return result;
 7         }
 8         ;
 9         result.add(0);
10         result.add(1);
11         for (int i = 1; i < n; i++) {
12             ArrayList<Integer> tmp = new ArrayList<Integer>(result);
13             Integer a = 1 << i;
14             for (int k = result.size() - 1; k >= 0; k--) {
15                 tmp.add(result.get(k) + a);
16             }
17             result = tmp;
18         }
19         return result;
20     }
21 }



Meng Lee 2013-12-24 12:06 鍙戣〃璇勮
]]>
[Leetcode] Multiply Stringshttp://www.aygfsteel.com/menglee/archive/2013/12/23/407912.htmlMeng LeeMeng LeeMon, 23 Dec 2013 03:59:00 GMThttp://www.aygfsteel.com/menglee/archive/2013/12/23/407912.htmlhttp://www.aygfsteel.com/menglee/comments/407912.htmlhttp://www.aygfsteel.com/menglee/archive/2013/12/23/407912.html#Feedback0http://www.aygfsteel.com/menglee/comments/commentRss/407912.htmlhttp://www.aygfsteel.com/menglee/services/trackbacks/407912.htmlGiven two numbers represented as strings, return multiplication of the numbers as a string.
Note: The numbers can be arbitrarily large and are non-negative.

瀵規(guī)瘡涓暟瀛楃浉涔橈紝璁板綍鍒頒竴涓暟緇勪腑錛岀劧鍚庡榪欎釜鏁板瓧鐨勬瘡涓厓绱犺繘琛岃繘浣嶆鏌ャ備富瑕佺浉涔樼殑鏃跺欒鍒嗗埆浠庝袱涓暟瀛楃殑鏈鍚庝竴浣嶅紑濮嬶紝榪樿璁板綍鍋忕Щ閲忋傚疄鐜板涓嬶細
 1 public class MultiplyStrings {
 2     public String multiply(String num1, String num2) {
 3         int length1 = num1.length();
 4         int length2 = num2.length();
 5         int[] m = new int[length1 + length2];
 6         for (int k = length2 - 1, offset2 = 0; k >= 0; k--, offset2++) {
 7             for (int i = length1 - 1, offset1 = 0; i >= 0; i--, offset1++) {
 8                 m[length1 + length2 - 1 - offset1 - offset2] += (num1.charAt(i) - '0') * (num2.charAt(k) - '0');
 9             }
10         }
11         int add = 0;
12         for (int t = length1 + length2 - 1; t >= 0; t--) {
13             int value = m[t] + add;
14             add = value / 10;
15             m[t] = value % 10;
16         }
17         StringBuffer sb = new StringBuffer();
18         int w = 0;
19         for (; w < length1 + length2; w++) {
20             if (m[w] != 0) break;
21         }
22         for (int e = w; e < length1 + length2; e++) {
23             sb.append(m[e]);
24         }
25         return sb.length() == 0 ? "0" : sb.toString();
26     }
27 }



Meng Lee 2013-12-23 11:59 鍙戣〃璇勮
]]>
[Leetcode] Search for a Rangehttp://www.aygfsteel.com/menglee/archive/2013/12/23/407903.htmlMeng LeeMeng LeeMon, 23 Dec 2013 01:58:00 GMThttp://www.aygfsteel.com/menglee/archive/2013/12/23/407903.htmlhttp://www.aygfsteel.com/menglee/comments/407903.htmlhttp://www.aygfsteel.com/menglee/archive/2013/12/23/407903.html#Feedback0http://www.aygfsteel.com/menglee/comments/commentRss/407903.htmlhttp://www.aygfsteel.com/menglee/services/trackbacks/407903.htmlGiven a sorted array of integers, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].
For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].

榪欎釜棰樼洰鏈夐掑綊鍜岄潪閫掑綊涓や釜瑙f硶銆?br />閫掑綊瑙f硶錛氳繖涓В娉曟瘮杈冪畝媧侊紝浠g爜濡備笅錛?br />
 1 public class SearchforaRange {
 2         public int[] searchRange(int[] A, int target) {
 3                 int low = findLow(A, target, 0, A.length - 1);
 4                 int high = findHigh(A, target, 0, A.length - 1);
 5                 int[] ret = new int[2];
 6                 ret[0] = low;
 7                 ret[1] = high;
 8                 return ret;
 9         }
10 
11         private int findLow(int[] A, int target, int l, int r) {
12                 int mid = 0;
13                 int ret = -1;
14                 while (l <= r) {
15                         mid = (l + r) / 2;
16                         if (A[mid] == target) {
17                                 ret = mid;
18                                 int next = findLow(A, target, l, mid - 1);
19                                 if (next != -1) {
20                                         ret = next;
21                                 }
22                                 break;
23                         } else if (A[mid] < target) {
24                                 l = mid + 1;
25                         } else {
26                                 r = mid - 1;
27                         }
28 
29                 }
30                 return ret;
31         }
32 
33         private int findHigh(int[] A, int target, int l, int r) {
34                 int mid = 0;
35                 int ret = -1;
36                 while (l <= r) {
37                         mid = (l + r) / 2;
38                         if (A[mid] == target) {
39                                 ret = mid;
40                                 int next = findHigh(A, target, mid + 1, r);
41                                 if (next != -1) {
42                                         ret = next;
43                                 }
44                                 break;
45                         } else if (A[mid] < target) {
46                                 l = mid + 1;
47                         } else {
48                                 r = mid - 1;
49                         }
50                 }
51                 return ret;
52         }
53 }

闈為掑綊瑙f硶錛氫互瀵繪壘宸﹁竟鐣屼負渚嬶紝榪欎釜瑙f硶鐨勬濊礬灝辨槸涓鐩村悜宸﹁繘琛屼簩鍒嗘煡鎵撅紝鐩村埌鎵懼埌鏈宸︾殑鐩爣鍏冪礌鎴栬呮渶宸︾殑鐩爣鍏冪礌鐨勪笅涓涓厓绱犮傚洜姝わ紝浜屽垎鏌ユ壘緇撴潫涔嬪悗錛岄渶瑕佸垽鏂壘鍒扮殑鍏冪礌鍒板簳鏄洰鏍囧厓绱犺繕鏄粬鐨勭涓涓笉婊¤凍鐨勫厓绱狅紝鐒跺悗鏍規(guī)嵁鎯呭喌榪斿洖涓嬫爣銆備唬鐮佸疄鐜板涓嬶細
 1 public class Solution {
 2     public int[] searchRange(int[] A, int target) {
 3         int left = findLeft(A, target);
 4         int right = findRight(A, target);
 5         return new int[] { left, right };
 6     }
 7 
 8     private int findLeft(int[] A, int target) {
 9         int i = 0, j = A.length - 1;
10         while (i < j) {
11             int mid = (i + j) / 2;
12             if (A[mid] < target) {
13                 i = mid + 1;
14             } else {
15                 j = mid - 1;
16             }
17         }
18         if (A[i] == target) return i;
19         if (i < A.length - 1 && A[i + 1] == target) return i + 1;
20         return -1;
21     }
22 
23     private int findRight(int[] A, int target) {
24         int i = 0, j = A.length - 1;
25         while (i < j) {
26             int mid = (i + j) / 2;
27             if (A[mid] > target) {
28                 j = mid - 1;
29             } else {
30                 i = mid + 1;
31             }
32         }
33         if (j >= 0 && A[j] == target)
34             return j;
35         if (j > 0 && A[j - 1] == target)
36             return j - 1;
37         return -1;
38     }
39 }


Meng Lee 2013-12-23 09:58 鍙戣〃璇勮
]]>
[Leetcode] Search Insert Positionhttp://www.aygfsteel.com/menglee/archive/2013/12/23/407896.htmlMeng LeeMeng LeeMon, 23 Dec 2013 01:11:00 GMThttp://www.aygfsteel.com/menglee/archive/2013/12/23/407896.htmlhttp://www.aygfsteel.com/menglee/comments/407896.htmlhttp://www.aygfsteel.com/menglee/archive/2013/12/23/407896.html#Feedback0http://www.aygfsteel.com/menglee/comments/commentRss/407896.htmlhttp://www.aygfsteel.com/menglee/services/trackbacks/407896.htmlGiven a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Here are few examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0

鏈鍏堝鏁扮粍榪涜浜屽垎鎼滅儲錛屽鏋滄壘鍒頒簡鐩爣鍏冪礌灝辮繑鍥炵浉搴旂殑index錛屽鏋滄渶緇堟病鏈夋壘鍒板搴旂殑鍏冪礌錛屽垯姣旇緝鏈鍚庝竴涓厓绱犱笌鐩爣鍏冪礌鐨勫ぇ灝忋傚疄鐜頒唬鐮佸涓嬶細
 1 public class Solution {
 2     public int searchInsert(int[] A, int target) {
 3         int length = A.length;
 4         if (A.length == 0) return 0;
 5         int i = 0, j = length - 1;
 6         while (i < j) {
 7             int mid = (i + j) / 2;
 8             if (A[mid] == target) return mid;
 9             if (A[mid] < target) {
10                 i = mid + 1;
11             } else {
12                 j = mid - 1;
13             }
14         }
15         return A[i] < target ? i + 1 : i;
16     }
17 }


Meng Lee 2013-12-23 09:11 鍙戣〃璇勮
]]>
[Leetcode] Longest Substring Without Repeating Charactershttp://www.aygfsteel.com/menglee/archive/2013/12/22/407877.htmlMeng LeeMeng LeeSun, 22 Dec 2013 12:07:00 GMThttp://www.aygfsteel.com/menglee/archive/2013/12/22/407877.htmlhttp://www.aygfsteel.com/menglee/comments/407877.htmlhttp://www.aygfsteel.com/menglee/archive/2013/12/22/407877.html#Feedback0http://www.aygfsteel.com/menglee/comments/commentRss/407877.htmlhttp://www.aygfsteel.com/menglee/services/trackbacks/407877.htmlGiven a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

鏈姣旇緝綆鍗曪紝闇瑕佹敞鎰忕殑鏄乏鎸囬拡鍙崇Щ鏃訛紝闇瑕佸皢瀹冩帬榪囩殑鍏冪礌浠巑ap涓Щ闄ゃ傚疄鐜頒唬鐮佸涓嬶細
 1 public class Solution {
 2     public int lengthOfLongestSubstring(String s) {
 3         int length = s.length();
 4         if (length == 0) return 0;
 5         Map<Character, Integer> map = new HashMap<Character, Integer>();
 6         int ret = 0;
 7         int count = 0;
 8         int start = 0;
 9         for (int i = 0; i < length; i++) {
10             char c = s.charAt(i);
11             if (map.containsKey(c)) {
12                 int newStart = map.remove(c).intValue() + 1;
13                 for (int j = start; j < newStart; j++) {
14                     map.remove(s.charAt(j));
15                 }
16                 start = newStart;
17                 ret = ret < count ? count : ret;
18                 count = i - start + 1;
19             } else {
20                 count++;
21             }
22             map.put(c, i);
23         }
24         return ret < count ? count : ret;
25     }
26 }


Meng Lee 2013-12-22 20:07 鍙戣〃璇勮
]]>
[Leetcode] Spiral Matrixhttp://www.aygfsteel.com/menglee/archive/2013/12/22/407874.htmlMeng LeeMeng LeeSun, 22 Dec 2013 08:59:00 GMThttp://www.aygfsteel.com/menglee/archive/2013/12/22/407874.htmlhttp://www.aygfsteel.com/menglee/comments/407874.htmlhttp://www.aygfsteel.com/menglee/archive/2013/12/22/407874.html#Feedback0http://www.aygfsteel.com/menglee/comments/commentRss/407874.htmlhttp://www.aygfsteel.com/menglee/services/trackbacks/407874.htmlGiven a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]
You should return [1,2,3,6,9,8,7,4,5].

鍙互涓虹煩闃佃緗笂涓嬪乏鍙沖洓涓竟鐣岋紝姣忔緇曠潃榪欏洓涓竟鐣屾墦鍗板厓绱犮傚疄鐜頒唬鐮佸涓嬶細
 1 public class Solution {
 2     public ArrayList<Integer> spiralOrder(int[][] matrix) {
 3         ArrayList<Integer> ret = new ArrayList<Integer>();
 4         if (matrix.length == 0) return ret;
 5         int upper = 0, bottom = matrix.length - 1;
 6         int left = 0, right = matrix[0].length - 1;
 7         int i = 0, j = 0;
 8         while (true) {
 9             for (i = left; i <= right; i++) {
10                 ret.add(matrix[upper][i]);
11             }
12             if (++upper > bottom) break;
13             for (j = upper; j <= bottom; j++) {
14                 ret.add(matrix[j][right]);
15             }
16             if (--right < left) break;
17             for (i = right; i >= left; i--) {
18                 ret.add(matrix[bottom][i]);
19             }
20             if (--bottom < upper) break;
21             for (j = bottom; j >= upper; j--) {
22                 ret.add(matrix[j][left]);
23             }
24             if (++left > right) break;
25         }
26         return ret;
27     }
28 }


Meng Lee 2013-12-22 16:59 鍙戣〃璇勮
]]>
[Leetcode] Longest Valid Parentheseshttp://www.aygfsteel.com/menglee/archive/2013/12/21/407857.htmlMeng LeeMeng LeeSat, 21 Dec 2013 13:28:00 GMThttp://www.aygfsteel.com/menglee/archive/2013/12/21/407857.htmlhttp://www.aygfsteel.com/menglee/comments/407857.htmlhttp://www.aygfsteel.com/menglee/archive/2013/12/21/407857.html#Feedback0http://www.aygfsteel.com/menglee/comments/commentRss/407857.htmlhttp://www.aygfsteel.com/menglee/services/trackbacks/407857.htmlGiven a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
For "(()", the longest valid parentheses substring is "()", which has length = 2.
Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4.

鏈鐨勪富瑕佹濊礬灝辨槸鏍囪閭d簺鎷彿鏄鍖歸厤鐨勩?br />鎴戜滑鍙互鍒╃敤涓涓竷?yōu)當鏁熬l勶紝濡傛灉浣嶇疆涓篿鐨勫間負true錛屽垯琛ㄧず絎琲涓嫭鍙鋒槸琚尮閰嶇殑錛岀劧鍚庢垜浠彧闇瑕佹眰榪炵畫涓簍rue鐨勫厓绱犵殑涓暟鍗沖彲銆傚疄鐜頒唬鐮佸涓嬶細
 1 public class LongestValidParentheses {
 2     public int longestValidParentheses(String s) {
 3         int length = s.length();
 4         if (length == 0)
 5             return 0;
 6         int left = 0;
 7         Stack<Integer> indexs = new Stack<Integer>();
 8         boolean[] record = new boolean[length];
 9         for (int i = 0; i < length; i++) {
10             if (s.charAt(i) == '(') {
11                 left++;
12                 indexs.push(i);
13             } else if (left > 0) {
14                 int idx = indexs.pop();
15                 record[idx] = true;
16                 record[i] = true;
17                 left--;
18             }
19         }
20         int ret = 0;
21         int current = 0;
22         for (int k = 0; k < length; k++) {
23             if (record[k]) {
24                 current++;
25             } else {
26                 ret = current > ret ? current : ret;
27                 current = 0;
28             }
29         }
30         return ret > current ? ret : current;
31     }
32 }


Meng Lee 2013-12-21 21:28 鍙戣〃璇勮
]]>
[Leetcode] Minimum Depth of Binary Treehttp://www.aygfsteel.com/menglee/archive/2013/12/21/407856.htmlMeng LeeMeng LeeSat, 21 Dec 2013 13:19:00 GMThttp://www.aygfsteel.com/menglee/archive/2013/12/21/407856.htmlhttp://www.aygfsteel.com/menglee/comments/407856.htmlhttp://www.aygfsteel.com/menglee/archive/2013/12/21/407856.html#Feedback0http://www.aygfsteel.com/menglee/comments/commentRss/407856.htmlhttp://www.aygfsteel.com/menglee/services/trackbacks/407856.htmlGiven a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

鏈鏈変袱縐嶈В娉曘?br />絎竴縐嶈В娉曪細瀵逛簩鍙夋爲榪涜BFS錛岀敱浜庢槸鎸夊眰閬嶅巻鐨勶紝鍥犳濡傛灉鍦ㄦ煇涓灞傚彂鐜頒簡涓涓彾瀛愯妭鐐癸紝閭d箞灝辨壘鍒頒簡鏈灝忔繁搴︼紝姝ゆ椂榪斿洖褰撳墠娣卞害鍗沖彲銆傚疄鐜頒唬鐮佸涓嬶細
 1 public class Solution {
 2     public int minDepth(TreeNode root) {
 3         if (root == nullreturn 0;
 4         int depth = 1;
 5         int currentLevel = 1;
 6         int nextLevel = 0;
 7         Queue<TreeNode> queue = new LinkedList<TreeNode>();
 8         queue.add(root);
 9         while (!queue.isEmpty()) {
10             TreeNode node = queue.remove();
11             currentLevel--;
12             if (node.left == null && node.right == null) {
13                 return depth;
14             }
15             if (node.left != null) {
16                 queue.add(node.left);
17                 nextLevel++;
18             }
19             if (node.right != null) {
20                 queue.add(node.right);
21                 nextLevel++;
22             }
23             if (currentLevel == 0) {
24                 if (nextLevel != 0) {
25                     depth++;
26                 }
27                 currentLevel = nextLevel;
28                 nextLevel = 0;
29             }
30         }
31         return depth;
32     }
33 }

絎簩縐嶈В娉曪細閲囩敤閫掑綊鐨勬濇兂錛屽垎鍒眰宸﹀彸瀛愭爲鐨勬渶灝忔繁搴︼紝姣旇緝涔嬪悗榪斿洖杈冨皬鍊箋傚疄鐜板涓嬶細
 1 public class MinimumDepthofBinaryTree {
 2     public int minDepth(TreeNode root) {
 3         if (root == null)
 4             return 0;
 5         if (root.left == null && root.right == null)
 6             return 1;
 7         else {
 8             int leftDepth = root.left != null ? minDepth(root.left)
 9                     : Integer.MAX_VALUE;
10             int rightDepth = root.right != null ? minDepth(root.right)
11                     : Integer.MAX_VALUE;
12             return Math.min(leftDepth, rightDepth) + 1;
13         }
14     }
15 }


Meng Lee 2013-12-21 21:19 鍙戣〃璇勮
]]>
[Leetcode] Permutations IIhttp://www.aygfsteel.com/menglee/archive/2013/12/20/407814.htmlMeng LeeMeng LeeFri, 20 Dec 2013 07:30:00 GMThttp://www.aygfsteel.com/menglee/archive/2013/12/20/407814.htmlhttp://www.aygfsteel.com/menglee/comments/407814.htmlhttp://www.aygfsteel.com/menglee/archive/2013/12/20/407814.html#Feedback1http://www.aygfsteel.com/menglee/comments/commentRss/407814.htmlhttp://www.aygfsteel.com/menglee/services/trackbacks/407814.htmlGiven a collection of numbers, return all possible permutations.
For example,
[1,2,3] have the following permutations:
[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].

鏁扮粍鍏ㄦ帓鍒楅鐩紝鍩烘湰鎬濇兂鏄姣忎竴涓瓧絎︿笌鍚庨潰鐨勫瓧絎︿綔浜ゆ崲錛屼互鐢熸垚鏂扮殑搴忓垪銆備負浜嗛槻姝㈤噸澶嶏紝浜ゆ崲涔嬪墠闇瑕佹鏌ヤ箣鍓嶆槸鍚﹀凡緇忓拰鍚屾牱鐨勫瓧絎︿覆鍋氳繃浜ゆ崲銆備唬鐮佸涓嬶細
 1 public class PermutationsII {
 2     public ArrayList<ArrayList<Integer>> permuteUnique(int[] num) {
 3         ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
 4         permuteUnique(num, 0, result);
 5         return result;
 6     }
 7 
 8     void permuteUnique(int[] num, int begin,
 9             ArrayList<ArrayList<Integer>> result) {
10         if (begin > num.length - 1) {
11             ArrayList<Integer> item = new ArrayList<Integer>();
12             for (int h = 0; h < num.length; h++) {
13                 item.add(num[h]);
14             }
15             result.add(item);
16         }
17         for (int end = begin; end < num.length; end++) {
18             if (isSwap(num, begin, end)) {
19                 swap(num, begin, end);
20                 permuteUnique(num, begin + 1, result);
21                 swap(num, begin, end);
22             }
23         }
24     }
25 
26     boolean isSwap(int[] arr, int i, int j) {
27         for (int k = i; k < j; k++) {
28             if (arr[k] == arr[j]) {
29                 return false;
30             }
31         }
32         return true;
33     }
34     
35     private void swap(int[] a, int i, int j) {
36         int tmp = a[i];
37         a[i] = a[j];
38         a[j] = tmp;
39     }
40 }


Meng Lee 2013-12-20 15:30 鍙戣〃璇勮
]]>
[Leetcode] Unique Binary Search Treeshttp://www.aygfsteel.com/menglee/archive/2013/12/20/407801.htmlMeng LeeMeng LeeFri, 20 Dec 2013 03:58:00 GMThttp://www.aygfsteel.com/menglee/archive/2013/12/20/407801.htmlhttp://www.aygfsteel.com/menglee/comments/407801.htmlhttp://www.aygfsteel.com/menglee/archive/2013/12/20/407801.html#Feedback0http://www.aygfsteel.com/menglee/comments/commentRss/407801.htmlhttp://www.aygfsteel.com/menglee/services/trackbacks/407801.htmlGiven n, how many structurally unique BST's (binary search trees) that store values 1...n?
For example,
Given n = 3, there are a total of 5 unique BST's.
   1          3     3      2      1
    \        /      /       / \       \
     3     2     1       1   3       2
    /     /        \                      \
   2    1          2                     3
鏈浣跨敤涓緇寸嚎鎬ц鍒掕В鍐熾?br />濡傛灉n絳変簬0鏃訛紝緇撴灉涓?錛?br />濡傛灉n絳変簬1鏃訛紝鍙湁涓涓妭鐐癸紝緇撴灉涓?錛?br />濡傛灉n絳変簬2鏃訛紝鏍硅妭鐐規(guī)湁涓ょ閫夋嫨錛岀粨鏋滀負2錛?br />濡傛灉n澶т簬3鏃訛紝鏍硅妭鐐規(guī)湁n縐嶉夋嫨錛岀‘瀹氭牴鑺傜偣鍚庡垎鍒綆楀乏鍙沖瓙鏍戠殑鍙兘鎯呭喌錛岀劧鍚庣浉涔樺氨鏄綋鍓嶆牴鑺傜偣涓嬫墍鏈夌殑鍙樺艦縐嶇被錛屼箣鍚庡湪姹傚拰鍗沖彲銆傜畻娉曞疄鐜板涓嬶細
 1 public class UniqueBinarySearchTrees {
 2     public int numTrees(int n) {
 3         if (n == 1)
 4             return 1;
 5         if (n == 2)
 6             return 2;
 7         int[] record = new int[n + 1];
 8         record[0] = 1;
 9         record[1] = 1;
10         record[2] = 2;
11         for (int i = 3; i <= n; i++) {
12             int tmp = 0;
13             for (int k = 0; k < i; k++) {
14                 tmp += (record[k] * record[i - k - 1]);
15             }
16             record[i] = tmp;
17         }
18         return record[n];
19     }
20 }


Meng Lee 2013-12-20 11:58 鍙戣〃璇勮
]]>
[Leetcode] Palindrome Partitioninghttp://www.aygfsteel.com/menglee/archive/2013/12/19/407778.htmlMeng LeeMeng LeeThu, 19 Dec 2013 09:03:00 GMThttp://www.aygfsteel.com/menglee/archive/2013/12/19/407778.htmlhttp://www.aygfsteel.com/menglee/comments/407778.htmlhttp://www.aygfsteel.com/menglee/archive/2013/12/19/407778.html#Feedback0http://www.aygfsteel.com/menglee/comments/commentRss/407778.htmlhttp://www.aygfsteel.com/menglee/services/trackbacks/407778.htmlGiven 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"]
]

榪欎釜棰樼洰鑰冭檻鐢ㄥ姩鎬佽鍒掕В棰橈紝鍏抽敭鍦ㄤ簬鏋勯犱竴涓В絀洪棿錛岀‘瀹歋鐨勪換鎰忓瓙涓睸(i, j)鏄笉鏄縐扮殑銆傚垽鏂爣鍑嗗涓嬶細
1銆佸鏋渋 == j錛屽垯S(i, j)鏄縐扮殑錛?br />2銆佸鏋渏 - i == 1 && S[i] == S[j]錛屽垯S(i, j)鏄縐扮殑錛?br />3銆佸鏋渏 - i > 1 && S[i] == S[j] && S(i + 1, j - 1)鏄縐扮殑錛屽垯S(i, j)涔熸槸瀵圭О鐨勩?br />鍦ㄦ瀯閫犲畬榪欐牱鐨勮В絀洪棿鍚庯紝灝卞彲浠ュ湪O(1)鏃墮棿鍐呭垽瀹氫換鎰忓瓙涓叉槸涓嶆槸瀵圭О鐨勪簡銆傜畻娉曞疄鐜板涓嬶細
 1 public class PalindromePartitioning {
 2     public ArrayList<ArrayList<String>> partition(String s) {
 3         ArrayList<ArrayList<String>> ret = new ArrayList<ArrayList<String>>();
 4         ArrayList<String> r = new ArrayList<String>();
 5         int length = s.length();
 6         boolean[][] map = new boolean[length][length];
 7         findPartition(s, 0, ret, r, map);
 8         return ret;
 9     }
10 
11     private void findPartition(String s, int start,
12             ArrayList<ArrayList<String>> ret, ArrayList<String> r,
13             boolean[][] map) {
14         int length = s.length();
15         if (start == length && r.size() != 0) {
16             ArrayList<String> clone = new ArrayList<String>(r);
17             ret.add(clone);
18         } else {
19             for (int j = start; j < length; j++) {
20                 if (start == j
21                         || (j - start > 1 && s.charAt(start) == s.charAt(j) && map[start + 1][j - 1])
22                         || (j - start == 1 && s.charAt(start) == s.charAt(j))) {
23                     map[start][j] = true;
24                     r.add(s.substring(start, j + 1));
25                     findPartition(s, j + 1, ret, r, map);
26                     r.remove(r.size() - 1);
27                 }
28             }
29         }
30     }
31 }


Meng Lee 2013-12-19 17:03 鍙戣〃璇勮
]]>
[Leetcode] Clone Graphhttp://www.aygfsteel.com/menglee/archive/2013/12/19/407756.htmlMeng LeeMeng LeeThu, 19 Dec 2013 02:36:00 GMThttp://www.aygfsteel.com/menglee/archive/2013/12/19/407756.htmlhttp://www.aygfsteel.com/menglee/comments/407756.htmlhttp://www.aygfsteel.com/menglee/archive/2013/12/19/407756.html#Feedback0http://www.aygfsteel.com/menglee/comments/commentRss/407756.htmlhttp://www.aygfsteel.com/menglee/services/trackbacks/407756.htmlClone an undirected graph. Each node in the graph contains a label and a list of its neighbors.
OJ's undirected graph serialization:
Nodes are labeled uniquely.
We use # as a separator for each node, and , as a separator for node label and each neighbor of the node.
As an example, consider the serialized graph {0,1,2#1,2#2,2}.
The graph has a total of three nodes, and therefore contains three parts as separated by #.
1. First node is labeled as 0. Connect node 0 to both nodes 1 and 2.
2. Second node is labeled as 1. Connect node 1 to node 2.
3. Third node is labeled as 2. Connect node 2 to node 2 (itself), thus forming a self-cycle.

Visually, the graph looks like the following:
       1
      / \
     /   \
    0 --- 2
         / \
         \_/

闇瑕佸鍘熷浘榪涜BFS鎼滅儲錛屽叾涓璖et<UndirectedGraphNode> visited瀵瑰凡緇忚闂繃鐨勮妭鐐硅繘琛岃褰曪紝Map<UndirectedGraphNode, UndirectedGraphNode> map鐢ㄦ潵璁板綍鏂拌佽妭鐐圭殑瀵瑰簲鍏崇郴銆備唬鐮佸疄鐜板涓嬶細
 1 import java.util.HashMap;
 2 import java.util.HashSet;
 3 import java.util.LinkedList;
 4 import java.util.Map;
 5 import java.util.Queue;
 6 import java.util.Set;
 7 
 8 public class CloneGraph {
 9     public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
10         if (node == null)
11             return node;
12         Queue<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>();
13         queue.add(node);
14         Set<UndirectedGraphNode> visited = new HashSet<UndirectedGraphNode>();
15         Map<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<UndirectedGraphNode, UndirectedGraphNode>();
16         while (!queue.isEmpty()) {
17             UndirectedGraphNode n = queue.remove();
18             if (visited.contains(n))
19                 continue;
20             visited.add(n);
21             UndirectedGraphNode clone;
22             if (!map.containsKey(n)) {
23                 clone = new UndirectedGraphNode(n.label);
24                 map.put(n, clone);
25             } else {
26                 clone = map.get(n);
27             }
28             for (UndirectedGraphNode child : n.neighbors) {
29                 queue.add(child);
30                 UndirectedGraphNode cloneChild;
31                 if (!map.containsKey(child)) {
32                     cloneChild = new UndirectedGraphNode(child.label);
33                     map.put(child, cloneChild);
34                 } else {
35                     cloneChild = map.get(child);
36                 }
37                 clone.neighbors.add(cloneChild);
38             }
39         }
40         return map.get(node);
41     }
42 }


Meng Lee 2013-12-19 10:36 鍙戣〃璇勮
]]>
[Leetcode] Gas Stationhttp://www.aygfsteel.com/menglee/archive/2013/12/19/407753.htmlMeng LeeMeng LeeThu, 19 Dec 2013 01:29:00 GMThttp://www.aygfsteel.com/menglee/archive/2013/12/19/407753.htmlhttp://www.aygfsteel.com/menglee/comments/407753.htmlhttp://www.aygfsteel.com/menglee/archive/2013/12/19/407753.html#Feedback0http://www.aygfsteel.com/menglee/comments/commentRss/407753.htmlhttp://www.aygfsteel.com/menglee/services/trackbacks/407753.htmlThere are N gas stations along a circular route, where the amount of gas at station i is gas[i]. 

You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.

Return the starting gas station's index if you can travel around the circuit once, otherwise return -1.

Note: The solution is guaranteed to be unique.

棣栧厛錛岃繖涓鐩鏄庣‘濡傛灉gas[0] + gas[1] + ... + gas[n] >= cost[0] + cost[1] + .. + cost[n]錛岄偅涔堣繖涓鐩竴瀹氭湁瑙c傚洜涓猴紝鏍規(guī)嵁鏉′歡縐婚」鍙緱錛?br />(gas[0] - cost[0]) + (gas[1] - cost[1]) + ... + (gas[n] - cost[n]) >= 0錛岀敱浜庢渶緇堢粨鏋滃ぇ浜庣瓑浜庨浂錛屽洜姝や竴瀹氬彲浠ラ氳繃鍔犳硶浜ゆ崲寰嬶紝寰楀埌涓涓簭鍒楋紝浣垮緱涓棿緇撴灉閮戒負闈炶礋銆傚洜姝ゅ彲浠ュ皢綆楁硶瀹炵幇濡備笅錛?br />
 1 public class GasStation {
 2     public int canCompleteCircuit(int[] gas, int[] cost) {
 3         int sum = 0, total = 0, len = gas.length, index = -1;
 4         for (int i = 0; i < len; i++) {
 5             sum += gas[i] - cost[i];
 6             total += gas[i] - cost[i];
 7             if (sum < 0) {
 8                 index = i;
 9                 sum = 0;
10             }
11         }
12         return total >= 0 ? index + 1 : -1;
13     }
14 }


Meng Lee 2013-12-19 09:29 鍙戣〃璇勮
]]>
[Leetcode] Word Ladderhttp://www.aygfsteel.com/menglee/archive/2013/12/19/407752.htmlMeng LeeMeng LeeThu, 19 Dec 2013 01:11:00 GMThttp://www.aygfsteel.com/menglee/archive/2013/12/19/407752.htmlhttp://www.aygfsteel.com/menglee/comments/407752.htmlhttp://www.aygfsteel.com/menglee/archive/2013/12/19/407752.html#Feedback0http://www.aygfsteel.com/menglee/comments/commentRss/407752.htmlhttp://www.aygfsteel.com/menglee/services/trackbacks/407752.htmlGiven two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that:
    1. Only one letter can be changed at a time
    2. Each intermediate word must exist in the dictionary
For example,
Given:
    start = "hit"
    end = "cog"
    dict = ["hot","dot","dog","lot","log"]
    As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
    return its length 5.
Note:
    1. Return 0 if there is no such transformation sequence.
    2. All words have the same length.
    3. All words contain only lowercase alphabetic characters.

絎竴涓濊礬鏄亶鍘哾ict涓殑姣忎竴涓厓绱狅紝鐪嬫槸涓嶆槸鍜屽綋鍓峸ord鍙浉宸竴涓瓧絎︼紝濡傛灉鏄垯浣滀負鏂扮殑褰撳墠word錛岀洿鍒板綋鍓峸ord涓巘arget鍙浉宸竴涓瓧絎︺傚疄鐜頒唬鐮佸涓嬶細
 1 public class Solution {
 2     public int ladderLength(String start, String end, HashSet<String> dict) {
 3         HashSet<String> trash = new HashSet<String>();
 4         return searchWordLadder(start, end, dict, trash) + 1;
 5     }
 6 
 7     private int searchWordLadder(String start, String end, HashSet<String> dict, HashSet<String> trash) {
 8         if (stringDiff(start, end) == 1) return 1;
 9         if (dict.size() == trash.size()) return 0;
10         int steps = Integer.MAX_VALUE;
11         for (String word : dict) {
12             if (!trash.contains(word) && stringDiff(start, word) == 1) {
13                 trash.add(word);
14                 int lt = searchWordLadder(word, end, dict, trash);
15                 if (lt != 0 && lt < steps) {
16                     steps = lt;
17                 }
18                 trash.remove(word);
19             }
20         }
21         return steps == Integer.MAX_VALUE ? 0 : steps + 1;
22     }
23     
24     private int stringDiff(String s1, String s2) {
25         int diff = 0;
26         int length = s1.length();
27         for (int i = 0; i < length; i++) {
28             if (s1.charAt(i) != s2.charAt(i)) {
29                 diff++;
30             }
31         }
32         return diff;
33     }
34 }
榪欎釜綆楁硶鍙互閫氳繃灝忔暟鎹祴璇曪紝浣嗘槸鍦ㄥぇ鏁版嵁涓嬫姤瓚呮椂閿欒銆備富瑕侀棶棰樻槸綆楁硶澶嶆潅搴﹁緝楂橈紝鐢變簬dict涓殑鍗曡瘝鏄貢搴忕殑錛屽洜姝ゆ渶鍧忔儏鍐典笅闇瑕侀亶鍘嗘墍鏈夊彲鑳界殑杞崲璺緞鎵嶈兘鍋氬嚭鍒ゆ柇銆?br />鏀瑰彉鎬濊礬錛屽叾瀹炲彲浠ラ氳繃trie鏍戠殑BFS鎼滅儲鑾峰緱緇撴灉錛岀敱浜嶣FS鏄垎灞傞亶鍘嗙殑錛屽洜姝ゆ壘鍒頒竴涓В涔嬪悗灝卞彲浠ラ┈涓婅繑鍥烇紝澶嶆潅搴︽槸O(N)錛孨鏄師鍗曡瘝鐨勯暱搴︺傚疄鐜頒唬鐮佸涓嬶細
 1 public class WordLadder {
 2     public int ladderLength(String start, String end, HashSet<String> dict) {
 3         if (dict.size() == 0)
 4             return 0;
 5         int currentLevel = 1;
 6         int nextLevel = 0;
 7         int step = 1;
 8         boolean found = false;
 9         Queue<String> st = new LinkedList<String>();
10         HashSet<String> visited = new HashSet<String>();
11         st.add(start);
12         while (!st.isEmpty()) {
13             String s = st.remove();
14             currentLevel--;
15             if (stringDiff(s, end) == 1) {
16                 found = true;
17                 step++;
18                 break;
19             } else {
20                 int length = s.length();
21                 StringBuffer sb = new StringBuffer(s);
22                 for (int i = 0; i < length; i++) {
23                     for (int j = 0; j < 26; j++) {
24                         char c = sb.charAt(i);
25                         sb.setCharAt(i, (char) ('a' + j));
26                         if (dict.contains(sb.toString())
27                                 && !visited.contains(sb.toString())) {
28                             nextLevel++;
29                             st.add(sb.toString());
30                             visited.add(sb.toString());
31                         }
32                         sb.setCharAt(i, c);
33                     }
34                 }
35             }
36             if (currentLevel == 0) {
37                 currentLevel = nextLevel;
38                 nextLevel = 0;
39                 step++;
40             }
41         }
42         return found ? step : 0;
43     }
44 
45     private int stringDiff(String s1, String s2) {
46         int diff = 0;
47         int length = s1.length();
48         for (int i = 0; i < length; i++) {
49             if (s1.charAt(i) != s2.charAt(i)) {
50                 diff++;
51             }
52         }
53         return diff;
54     }
55 }
鍏朵腑鍒╃敤浜嗛槦鍒楀trie鏍戣繘琛孊FS銆?/div>

Meng Lee 2013-12-19 09:11 鍙戣〃璇勮
]]> 主站蜘蛛池模板: 津市市| 二连浩特市| 花莲市| 松桃| 梅河口市| 奉新县| 碌曲县| 浦北县| 绩溪县| 宿州市| 太白县| 九寨沟县| 水富县| 阿瓦提县| 康马县| 耒阳市| 白银市| 闻喜县| 阳泉市| 扎兰屯市| 青浦区| 方山县| 宁武县| 沈阳市| 外汇| 开江县| 灌阳县| 绥滨县| 凤山市| 从化市| 高青县| 高尔夫| 临颍县| 讷河市| 临高县| 临漳县| 井研县| 松原市| 新田县| 那曲县| 如东县|