分割回文串
问题描述
给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。
返回 s 所有可能的分割方案。
示例:
题解
回溯法
回溯法:用深度优先搜索来实现的优化的穷举法。
模板:
递归回溯:
void backtrack (参数){
if (终止条件) output();
else{
for (int i=f(n,t);i<=g(n,t);i++) {
处理节点;
if (constraint()&&bound()) backtrack();//如果满足约束条件则递归
回溯,撤销对节点的处理;
}
}
}
迭代回溯:
void iterativeBacktrack (){
int t=1;//t为层数
while (t>0) {
if (f(n,t)<=g(n,t))
for (int i=f(n,t);i<=g(n,t);i++) {
x[t]=h(i);
if (constraint(t)&&bound(t)) {
if (solution(t)) output(x);
else t++;
}
}
else t--;
}
}
本题代码:
public class Solution {
public List<List<String>> partition(String s) {
int len = s.length();
List<List<String>> res = new ArrayList<>();
if (len == 0) {
return res;
}
Deque<String> path = new ArrayDeque<>();
backtracking(s, 0, len, path, res);
return res;
}
public void backtracking(String s, int start, int len, Deque<String> path, List<List<String>> res) {
if (start == len) {
//终止条件
res.add(new ArrayList<>(path));
return;
}else{
for (int i = start; i < len; i++) {
if (isPalindrome(s, start, i)) {
//如果是回文串则递归
path.addLast(s.substring(start, i + 1));
backtracking(s, i + 1, len, path, res);
path.removeLast();
}
}
}
}
public boolean isPalindrome(String s, int low, int high) {
while (low < high) {
if (s.charAt(low) != s.charAt(high)) {
return false;
}
low++;
high--;
}
return true;
}
}
有效的字母异位词
问题描述
给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。
说明:
- 字母异位词指字母相同,但排列不同的字符串。
- 你可以假设字符串只包含小写字母。
进阶
- 如果输入字符串包含 unicode 字符怎么办?你能否调整你的解法来应对这种情况?
题解
hash表
思想:
- 首先判断两个字符串长度是否相等,不相等则直接返回 false
- 若相等,则初始化 26 个字母哈希表,遍历字符串 s 和 t
- s 负责在对应位置增加,t 负责在对应位置减少
- 如果哈希表的值都为 0,则二者是字母异位词
class Solution {
public boolean isAnagram(String s, String t) {
if(s.length() != t.length())
return false;
int[] alpha = new int[26];
for(int i = 0; i< s.length(); i++) {
alpha[s.charAt(i) - 'a'] ++;
alpha[t.charAt(i) - 'a'] --;
}
for(int i=0;i<26;i++)
if(alpha[i] != 0)
return false;
return true;
}
}
作者:guanpengchn
链接:https://leetcode-cn.com/problems/valid-anagram/solution/hua-jie-suan-fa-242-you-xiao-de-zi-mu-yi-wei-ci-by/
来源:力扣(LeetCode)
排序
此题解来自官解
思想:t 是 s 的异位词等价于「两个字符串排序后相等」。因此我们可以对字符串 s 和 t 分别排序,看排序后的字符串是否相等即可判断。此外,如果 s 和 tt的长度不同,t 必然不是 s 的异位词。
class Solution {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) {
return false;
}
char[] str1 = s.toCharArray();
char[] str2 = t.toCharArray();
Arrays.sort(str1);
Arrays.sort(str2);
return Arrays.equals(str1, str2);
}
}