Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit941270b

Browse files
MEDIUM/src/medium/PalindromePartitioning.java
1 parentf6feb4a commit941270b

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
packagemedium;
2+
3+
importjava.util.ArrayList;
4+
importjava.util.List;
5+
6+
publicclassPalindromePartitioning {
7+
8+
9+
publicList<List<String>>partition(Strings) {
10+
List<List<String>>result =newArrayList();
11+
intn =s.length();
12+
boolean[][]dp =newboolean[n][n];
13+
for(inti =0;i <n;i++){
14+
for(intj =0;j <=i;j++){
15+
if(s.charAt(j) ==s.charAt(i) && (j+1 >=i-1 ||dp[j+1][i-1])){// j+1 >= i-1 means j and i are adjance to each other or only one char apart from each other
16+
//dp[j+1][i-1] means its inner substring is a palindrome, so as long as s.charAt(j) == s.charAt(i), then dp[j][i] must be a palindrome.
17+
dp[j][i] =true;
18+
}
19+
}
20+
}
21+
22+
for(boolean[]list :dp){
23+
for(booleanb :list){
24+
System.out.print(b +", ");
25+
}
26+
System.out.println();
27+
}
28+
System.out.println();
29+
30+
backtracking(s,0,dp,newArrayList(),result);
31+
32+
returnresult;
33+
}
34+
35+
voidbacktracking(Strings,intstart,boolean[][]dp,List<String>temp,
36+
List<List<String>>result) {
37+
if (start ==s.length()) {
38+
List<String>newTemp =newArrayList(temp);
39+
result.add(newTemp);
40+
}
41+
for (inti =start;i <s.length();i++) {
42+
if (dp[start][i]) {
43+
temp.add(s.substring(start,i +1));
44+
backtracking(s,i +1,dp,temp,result);
45+
temp.remove(temp.size() -1);
46+
}
47+
}
48+
}
49+
50+
51+
publicstaticvoidmain(String...strings){
52+
PalindromePartitioningtest =newPalindromePartitioning();
53+
Strings ="aab";
54+
List<List<String>>result =test.partition(s);
55+
for(List<String>list :result){
56+
for(Stringstr :list){
57+
System.out.print(str +", ");
58+
}
59+
System.out.println();
60+
}
61+
}
62+
63+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp