|
2 | 2 |
|
3 | 3 | public class Main {
|
4 | 4 |
|
5 |
| - public String longestPalindrome(String s) { |
6 |
| - int[] res = new int[2]; |
7 |
| - for (int i = 0; i < s.length(); i++) { |
8 |
| - helper(s, i - 1, i + 1, res); |
9 |
| - helper(s, i, i + 1, res); |
10 |
| - } |
11 |
| - return s.substring(res[1], res[1] + res[0]); |
12 |
| - } |
| 5 | + public int trap(int[] height) { |
| 6 | + int[] left = new int[height.length]; |
| 7 | + int[] right = new int[height.length]; |
13 | 8 |
|
14 |
| - private void helper(String s, int left, int right, int[] res) { |
15 |
| - for ( ; left >= 0 && right < s.length(); left--, right++) { |
16 |
| - if (s.charAt(left) != s.charAt(right)) { |
17 |
| - break; |
18 |
| - } |
| 9 | + for (int i = 1; i < height.length; i++) { |
| 10 | + left[i] = Math.max(left[i - 1], height[i - 1]); |
19 | 11 | }
|
20 |
| - int len = --right - ++left + 1; |
21 |
| - if (len > res[0]) { |
22 |
| - res[0] = len; |
23 |
| - res[1] = left; |
| 12 | + for (int i = height.length - 2; i >= 0; i--) { |
| 13 | + right[i] = Math.max(right[i + 1], height[i + 1]); |
24 | 14 | }
|
| 15 | + int rain = 0; |
| 16 | + for (int i = 1; i < height.length - 1; i++) { |
| 17 | + rain += Math.max(0, Math.min(left[i], right[i]) - height[i]); |
| 18 | + } |
| 19 | + return rain; |
25 | 20 | }
|
26 | 21 |
|
27 |
| -// public static String longestPalindrome(String s) { |
28 |
| -// if (s.length() == 0) { |
29 |
| -// return ""; |
30 |
| -// } |
31 |
| -// int max = 0, idx = -1; |
32 |
| -// for (int i = 0; i < s.length(); i++) { |
33 |
| -// int len = findLen(s, i); |
34 |
| -// if (len > max) { |
35 |
| -// max = len; |
36 |
| -// idx = i; |
37 |
| -// } |
38 |
| -// } |
39 |
| -// if (max % 2 == 0) { |
40 |
| -// return s.substring(idx - max / 2 + 1, idx + max / 2 + 1); |
41 |
| -// } else { |
42 |
| -// return s.substring(idx - max / 2, idx + max / 2 + 1); |
43 |
| -// } |
44 |
| -// } |
45 |
| -// |
46 |
| -// private static int findLen(String s, int index) { |
47 |
| -// int len1 = 1; |
48 |
| -// for (int i = 1; i <= s.length(); i++) { |
49 |
| -// int i1 = index - i, i2 = index + i; |
50 |
| -// if (i1 < 0 || i2 >= s.length() || s.charAt(i1) != s.charAt(i2)) { |
51 |
| -// break; |
52 |
| -// } |
53 |
| -// len1 += 2; |
54 |
| -// } |
55 |
| -// int len2 = 0; |
56 |
| -// for (int i = 0; i < s.length(); i++) { |
57 |
| -// int i1 = index - i, i2 = index + i + 1; |
58 |
| -// if (i1 < 0 || i2 >= s.length() || s.charAt(i1) != s.charAt(i2)) { |
59 |
| -// break; |
60 |
| -// } |
61 |
| -// len2 += 2; |
62 |
| -// } |
63 |
| -// return Math.max(len1, len2); |
64 |
| -// } |
65 |
| - |
66 | 22 | public static void main(String[] args) {
|
67 |
| - String s = longestPalindrome("cbbd"); |
68 |
| - System.out.println(s); |
69 | 23 | }
|
70 | 24 | }
|
0 commit comments