Skip to content

Commit 0e61d64

Browse files
committed
fd
1 parent b82c796 commit 0e61d64

File tree

3 files changed

+4
-38
lines changed

3 files changed

+4
-38
lines changed

solution/src/main/java/com/inuker/solution/ShortestPalindrome.java

Lines changed: 3 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -9,30 +9,16 @@
99
*/
1010
public class ShortestPalindrome {
1111
/**
12-
* 其实只要将s与s的逆序串拼接在一起,求最长公共子串,逆序串中刨除这个最长公共子串,就是要加到s前面的
12+
* 其实只要将s与s的逆序串拼接在一起,求最长公共子串
13+
* 逆序串中从末尾刨除这个最长公共子串,就是要加到s前面的部分
14+
* 比如对abcd,其逆序为dcba,拼接为abcddcba,最长公共子串为a,因此dcba刨除a后为dcb,即为要加到abcd前面的部分
1315
*/
1416
public String shortestPalindrome(String s) {
1517
StringBuilder builder = new StringBuilder(s);
1618
return builder.reverse().substring(0, s.length() - getCommonLength(s)) + s;
1719
}
1820

1921
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) {
3622
String rev = new StringBuilder(str).reverse().toString();
3723
return getCommonLength(str + rev, str.length());
3824
}

solution/src/main/java/com/inuker/solution/StrStr.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
public class StrStr {
88

99
// 这里非常重要的是i<=len1-len2,如果没有这个会超时
10+
// 比如needle非常长的时候
1011
public int strStr(String haystack, String needle) {
1112
int l1 = haystack.length(), l2 = needle.length();
1213
for (int i = 0, j; i + l2 - 1 < l1; i++) {

test/src/main/java/com/inuker/test/main.java

Lines changed: 0 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -28,27 +28,6 @@
2828
public class main {
2929

3030
public static void main(String[] args) {
31-
System.out.println(multiply("99", "100"));
3231
}
3332

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-
}
5433
}

0 commit comments

Comments
 (0)