45 lines
1.1 KiB
Java
45 lines
1.1 KiB
Java
|
package com.zerroi.leetcode.Three27;
|
||
|
|
||
|
import java.util.ArrayList;
|
||
|
import java.util.List;
|
||
|
|
||
|
public class CountSubstrings {
|
||
|
public static void main(String[] args) {
|
||
|
Solution solution = new Solution();
|
||
|
String s = "abc";
|
||
|
int res = solution.countSubstrings(s);
|
||
|
System.out.println("res = " + res);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
class Solution {
|
||
|
private List<String> path = new ArrayList<>();
|
||
|
public int countSubstrings(String s) {
|
||
|
backtrack(s, 0);
|
||
|
return path.size();
|
||
|
}
|
||
|
private void backtrack(String s, int start) {
|
||
|
if (start >= s.length()) {
|
||
|
return;
|
||
|
}
|
||
|
for (int i = start; i < s.length(); i++) {
|
||
|
if (isPalindrome(s, start, i)) {
|
||
|
String str = s.substring(start, i + 1);
|
||
|
path.add(str);
|
||
|
} else {
|
||
|
continue;
|
||
|
}
|
||
|
backtrack(s, i + 1);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
private boolean isPalindrome(String s, int startIndex, int end) {
|
||
|
for (int i = startIndex, j = end; i < j; i++, j--) {
|
||
|
if (s.charAt(i) != s.charAt(j)) {
|
||
|
return false;
|
||
|
}
|
||
|
}
|
||
|
return true;
|
||
|
}
|
||
|
}
|