File tree Expand file tree Collapse file tree 3 files changed +4
-38
lines changed
solution/src/main/java/com/inuker/solution
test/src/main/java/com/inuker/test Expand file tree Collapse file tree 3 files changed +4
-38
lines changed Original file line number Diff line number Diff line change 9
9
*/
10
10
public class ShortestPalindrome {
11
11
/**
12
- * 其实只要将s与s的逆序串拼接在一起,求最长公共子串,逆序串中刨除这个最长公共子串,就是要加到s前面的
12
+ * 其实只要将s与s的逆序串拼接在一起,求最长公共子串
13
+ * 逆序串中从末尾刨除这个最长公共子串,就是要加到s前面的部分
14
+ * 比如对abcd,其逆序为dcba,拼接为abcddcba,最长公共子串为a,因此dcba刨除a后为dcb,即为要加到abcd前面的部分
13
15
*/
14
16
public String shortestPalindrome (String s ) {
15
17
StringBuilder builder = new StringBuilder (s );
16
18
return builder .reverse ().substring (0 , s .length () - getCommonLength (s )) + s ;
17
19
}
18
20
19
21
private int getCommonLength (String str ) {
20
- StringBuilder builder = new StringBuilder (str );
21
- String rev = new StringBuilder (str ).reverse ().toString ();
22
- builder .append ("#" ).append (rev );
23
- int [] p = new int [builder .length ()];
24
- for (int i = 1 ; i < p .length ; i ++) {
25
- int j = p [i - 1 ];
26
- while (j > 0 && builder .charAt (i ) != builder .charAt (j )) j = p [j - 1 ];
27
- p [i ] = j == 0 ? (builder .charAt (i ) == builder .charAt (0 ) ? 1 : 0 ) : j + 1 ;
28
- }
29
- return p [p .length - 1 ];
30
- }
31
-
32
- /**
33
- * 更直观的写法
34
- */
35
- private int getCommonLength2 (String str ) {
36
22
String rev = new StringBuilder (str ).reverse ().toString ();
37
23
return getCommonLength (str + rev , str .length ());
38
24
}
Original file line number Diff line number Diff line change 7
7
public class StrStr {
8
8
9
9
// 这里非常重要的是i<=len1-len2,如果没有这个会超时
10
+ // 比如needle非常长的时候
10
11
public int strStr (String haystack , String needle ) {
11
12
int l1 = haystack .length (), l2 = needle .length ();
12
13
for (int i = 0 , j ; i + l2 - 1 < l1 ; i ++) {
Original file line number Diff line number Diff line change 28
28
public class main {
29
29
30
30
public static void main (String [] args ) {
31
- System .out .println (multiply ("99" , "100" ));
32
31
}
33
32
34
- public static String multiply (String num1 , String num2 ) {
35
- int l1 = num1 .length (), l2 = num2 .length ();
36
- int [] result = new int [l1 + l2 ];
37
- for (int i = l1 - 1 ; i >= 0 ; i --) {
38
- for (int j = l2 - 1 ; j >= 0 ; j --) {
39
- int n1 = num1 .charAt (i ) - '0' ;
40
- int n2 = num2 .charAt (j ) - '0' ;
41
- int n = result [i + j + 1 ] + n1 * n2 ;
42
- result [i + j + 1 ] = n % 10 ;
43
- result [i + j ] += n / 10 ;
44
- }
45
- }
46
- StringBuilder sb = new StringBuilder ();
47
- for (int i = 0 ; i < result .length ; i ++) {
48
- if (result [i ] != 0 || sb .length () > 0 ) {
49
- sb .append (result [i ]);
50
- }
51
- }
52
- return sb .length () == 0 ? "0" : sb .toString ();
53
- }
54
33
}
You can’t perform that action at this time.
0 commit comments