利用堆栈:
http://oj.leetcode.com/problems/evaluate-reverse-polish-notation/
http://oj.leetcode.com/problems/longest-valid-parentheses/ (也可以用一维数组,贪心)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | 1 . 使用栈来保存 '(' 2 . tmp 表示当前计算的一套完整的括号集的长度。完整的指的是消耗掉栈中所有的 '(' . 3 . sum 表示数个完整的括号集的总长。 例子: 有一套完整的括号集,可以加到前面的一整套括号集上 () (()()) 1 2 第二套括号集可以加过来 4 . 不完整的括号集: 这种情况也是需要计算的。也可能是一个未完成的括号集,比如: () (()() 在这里 ()() 是一个未完成的括号集,可以独立出来计算,作为 阶段性的结果 5 . 栈为空时,出现一个 ')' ,可以将sum置 0 . public class Solution { public int longestValidParentheses(String s) { if (s == null ) { return 0 ; } Stack<Integer> stk = new Stack<Integer>(); int sum = 0 ; int tmp = 0 ; int max = 0 ; for ( int i = 0 ; i < s.length(); i++) { char c = s.charAt(i); if (c == '(' ) { stk.push(i); } else { if (stk.isEmpty()) { // 栈中没有'(',出现')', 则必须重置计算 sum = 0 ; continue ; } // count the temporary lenght: // like: (()()() // tmp = 2. tmp = i - stk.pop() + 1 ; if (stk.isEmpty()) { // 有一套完整的括号集,可以加到前面的一整套括号集上 // () (()()) // 1 2 第二套括号集可以加过来 sum += tmp; max = Math.max(sum, max); } else { // 也可能是一个未完成的括号集,比如: // () (()() 在这里 ()() 是一个未完成的括号集,可以独立出来计算,作为 // 阶段性的结果 tmp = i - stk.peek(); max = Math.max(tmp, max); } } } return max; } } |
http://oj.leetcode.com/problems/valid-parentheses/(完成)
http://oj.leetcode.com/problems/largest-rectangle-in-histogram/
特别注意细节:http://oj.leetcode.com/problems/trapping-rain-water/
多种数据结构:
http://oj.leetcode.com/problems/lru-cache/
http://oj.leetcode.com/problems/substring-with-concatenation-of-all-words/ (注意遍历方法)
HASH:http://oj.leetcode.com/problems/longest-consecutive-sequence/
Search in Rotated Sorted Array
(i.e., 0 1 2 4 5 6 7
might become 4 5 6 7 0 1 2
).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | public class Solution { public int search( int [] A, int target) { if (A == null || A.length == 0 ) { return - 1 ; } int start = 0 ; int end = A.length - 1 ; int mid; while (start + 1 < end) { mid = start + (end - start) / 2 ; if (A[mid] == target) { return mid; } if (A[start] < A[mid]) { // situation 1, red line if (A[start] <= target && target <= A[mid]) { end = mid; } else { start = mid; } } else { // situation 2, green line if (A[mid] <= target && target <= A[end]) { start = mid; } else { end = mid; } } } // while if (A[start] == target) { return start; } if (A[end] == target) { return end; } return - 1 ; } } |