- 前缀树
- 降序排序字符串
- 最小字典序
- 判断异位字符串
- 组合异位字符串
- 打印一个字符串的全部子序列
- 有效括号
- 整数反转
- 不含有重复字符的 最长子串 的长度
- 大数之和
- 字符串的全排列
1.前缀树
思路:
1.用路径表示字符
2.每个节点有path标记表示以这个字符为前缀有多少
3.每个节点有end标记表示有多少个相同字符串加了进来
public static class PrefixTree {
private int path;
private int end;
private PrefixTree[] nexts;
public PrefixTree() {
path = 0;
end = 0;
nexts = new PrefixTree[26];
}
}
public static class Prefix{
private PrefixTree tree;
public Prefix(){
tree = new PrefixTree();
}
//插入新字符串
public void insert(String string){
//判空
if (string == null || string.equals("")){
return;
}
PrefixTree curTree = tree;
char[] chars = string.toCharArray();
int index;
for (int i = 0;i < chars.length;i++){
index = chars[i] - 'a';
if (curTree.nexts[index] == null){
curTree.nexts[index] = new PrefixTree();
}
curTree = curTree.nexts[index];
curTree.path++;
}
curTree.end++;
}
//查询前缀
public int findPrefix(String string){
//判空
if (string == null || string.equals("")){
return 0;
}
PrefixTree curTree = tree;
char[] chars = string.toCharArray();
int index;
for (int i = 0;i < chars.length;i++){
index = chars[i] - 'a';
if (curTree.nexts[index] == null){
return 0;
}
curTree = curTree.nexts[index];
}
return curTree.path;
}
//查询字符串
public int findString(String string){
//判空
if (string == null || string.equals("")){
return 0;
}
PrefixTree curTree = tree;
char[] chars = string.toCharArray();
int index;
for (int i = 0;i < chars.length;i++){
index = chars[i] - 'a';
if (curTree.nexts[index] == null){
return 0;
}
curTree = curTree.nexts[index];
}
return curTree.end;
}
//删除字符串
public void delete(String string){
//判空
if (string == null || string.equals("")){
return;
}
if (findString(string) > 0){
PrefixTree curTree = tree;
char[] chars = string.toCharArray();
int index;
for (int i = 0;i < chars.length;i++){
index = chars[i] - 'a';
if (curTree.nexts[index] == null){
return;
}
curTree = curTree.nexts[index];
curTree.path--;
}
curTree.end--;
}
}
}
2.降序频率排序字符串
题目:
给定一个字符串,请将字符串里的字符按照出现的频率降序排列。
思路:
1.创建一个Node类用于保存char信息:char的字符和char出现的次数
2.将字符串转为数组
3.把字符出现信息丢进hashmap里
4.从hashmap得到的信息放进优先级队列
5.从优先级队列中一一弹出结点信息并打印
//时间 77%
//空间 82%
public static String frequencySort(String s) {
char[] chars = s.toCharArray();
HashMap<Character,Integer> hashMap = new HashMap<>();
for (char c:
chars) {
int number = hashMap.getOrDefault(c,0) + 1;
hashMap.put(c,number);
}
PriorityQueue<Node> queue = new PriorityQueue<>(new IdAscendingComparator());
for (char c:
hashMap.keySet()) {
queue.add(new Node(c,hashMap.get(c)));
}
StringBuilder sb = new StringBuilder();
while (!queue.isEmpty()) {
Node poll = queue.poll();
int k = poll.number;
while (k != 0) {
sb.append(poll.c);
k--;
}
}
return sb.toString();
}
static class Node{
public char c;
public int number;
public Node(char c, int number) {
this.c = c;
this.number = number;
}
}
public static class IdAscendingComparator implements Comparator<Node> {
@Override
public int compare(Node node1, Node node2) {
return node2.number - node1.number;
}
}
3.最小字典序
题目:
给定一个字符串类型的数组strs,找到一种拼接方式,使得把所有字 符串拼起来之后形成的字符串具有 最低的字典序。
思路
贪心算法
比较两个字符拼接后的大小
static class MyCompartor implements Comparator<String>{
@Override
public int compare(String s1, String s2) {
return (s1 + s2).compareTo(s2 + s1);
}
}
public static String lowestString(String[] string){
if (string == null || string.length == 0){
return "";
}
Arrays.sort(string,new MyCompartor());
String res = "";
for (int i = 0;i < string.length;i++){
res += string[i];
}
return res;
}
4.判断异位字符串
题目:
给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。
思路1
hashmap
1.用一个hasnmap装第一个字符串所有信息
2.遍历第二个字符串
如果没有当前字符 -> false
如果有当前字符 -> 将频率-1
如果频率=-1 -> false
//时间25.84%
//空间11.31%
public static boolean isAnagram(String s, String t) {
if (s == null || t == null || s.length() != t.length()){
return false;
}
HashMap<Character,Integer> hashMap1 = new HashMap<>();
for (int i = 0;i < s.length();i++){
char c = s.charAt(i);
int number = hashMap1.getOrDefault(c, 0) + 1;
hashMap1.put(c,number);
}
boolean isAnagram = true;
for (int i = 0;i < t.length();i ++){
char c = t.charAt(i);
isAnagram = hashMap1.containsKey(c);
if (!isAnagram){
break;
}
int number = hashMap1.get(c) - 1;
if (number == -1){
isAnagram = false;
break;
}
hashMap1.put(c,number);
}
return isAnagram;
}
思路2:
将两个字符串转换为数组
将数组排序
比较两个数组
//时间86.63%
//空间40.24%
public static boolean isAnagram(String s, String t) {
if (s == null || t == null || s.length() != t.length()){
return false;
}
char[] chars1 = s.toCharArray();
char[] chars2 = t.toCharArray();
Arrays.sort(chars1);
Arrays.sort(chars2);
return Arrays.equals(chars1, chars2);
}
思路3
投票算法
用一个26大小数组保存第一个字符串出现的次数信息
遍历第二个字符串,再相应的位置上-1
一旦有=-1的 -> false
public static boolean isAnagram(String s, String t) {
if (s == null || t == null || s.length() != t.length()){
return false;
}
int[] help = new int[26];
for (int i = 0;i < s.length();i++){
int index = s.charAt(i) - 'a';
help[index]++;
}
for (int i = 0;i < t.length();i++){
int index = t.charAt(i) - 'a';
help[index]--;
if (help[index] < 0){
return false;
}
}
return true;
}
5.组合异位字符串
题目:
给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
思路1
map -> K保存排列后字符 V保存一个List<Sting>数组保存原字符串
1.遍历字符串数组
2.将字符串排好序(K)
3.将排好序的字符从map中查看是否存在
4.加入到map中
5.返回map.values()
//时间 46.30%
//空间 35.37%
public static List<List<String>> groupAnagrams(String[] strs) {
//K = String(排好序) V = List<Sting>(存放相同的异位单词)
Map<String,List<String>> hashMap = new HashMap<>();
for (String str : strs) {
//排序
char[] chars = str.toCharArray();
Arrays.sort(chars);
//得到 K
String s = Arrays.toString(chars);
//取出 V
List<String> list = hashMap.getOrDefault(s, new ArrayList<>());
list.add(str);
hashMap.put(s, list);
}
return new ArrayList<>(hashMap.values());
}
思路2:
map -> K保存排列后字符 V保存一个List<Sting>数组保存原字符串
1.用数组计数
2.将数组得到的字符串作为K
//时间 45.68%
//空间 14.24%
public static List<List<String>> groupAnagrams(String[] strs) {
Map<String,List<String>> map = new HashMap<>();
for (String s:
strs) {
int[] counts = new int[26];
for (int i = 0;i < s.length();i++){
char c = s.charAt(i);
//计数
counts[c - 'a']++;
}
StringBuilder builder = new StringBuilder();
//得到K
for (int j = 0;j < counts.length;j++){
if (counts[j] != 0){
builder.append((char)('a' + j));
builder.append(counts[j]);
}
}
String key = builder.toString();
List<String> list = map.getOrDefault(key, new ArrayList<>());
list.add(s);
map.put(key,list);
}
return new ArrayList<>(map.values());
}
6.打印一个字符串的全部子序列
//res是上级做完决策后,扔给我的字符串
public static void printAllSub(char[] str, int i, String res) {
//i到最后,再无决策
if(i == str.length) {
System.out.println(res);
return;
}
//i指向的字符,要或者不要两种情况,两条路分别走
printAllSub(str, i + 1, res); //不要
printAllSub(str, i + 1, res + String.valueOf(str[i])); //要
}
7.有效括号
题目:
给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串 s ,判断字符串是否有效
//时间 99.14%
//空间 53.57%
public boolean _1_isValid(String s) {
StringBuilder stringBuilder = new StringBuilder();
int length = s.length();
int top = -1;
for (int i = 0; i < length; i++) {
char c = s.charAt(i);
if ((stringBuilder.length()>0) &&
(c == ')' && stringBuilder.charAt(top) == '(' ||
c == ']' && stringBuilder.charAt(top) == '[' ||
c == '}' && stringBuilder.charAt(top) == '{')){
stringBuilder.deleteCharAt(top--);
}else {
stringBuilder.append(c);
top++;
}
}
return stringBuilder.length() == 0;
}
8.整数反转
题目;给你一个 32 位的有符号整数 x ,返回将 x 中的数字部分反转后的结果。
//时间 100
//空间 90.52
public int reverse(int x) {
int res = 0;
while (x != 0){
//循环没有结束 -> 如果res*10已经越界则必然越界
if (res < Integer.MIN_VALUE / 10 || res > Integer.MAX_VALUE / 10) {
return 0;
}
//得到个位数
int num2 = x % 10;
//去除最后一位数
x = x / 10;
//记录个位数
res = res*10 + num2;
}
return res;
}
9.不含有重复字符的 最长子串 的长度
10.大数之和
题目:
给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和并同样以字符串形式返回。
你不能使用任何內建的用于处理大整数的库(比如 BigInteger), 也不能直接将输入的字符串转换为整数形式。
//时间 95.45%
//空间 96.55%
public String addStrings(String num1, String num2) {
//记录两个指针 和 判断是否有进位
int i = num1.length() - 1, j = num2.length() - 1, add = 0;
StringBuffer ans = new StringBuffer();
while (i >= 0 || j >= 0 || add != 0) {
//当位数不足时,补零
int x = i >= 0 ? num1.charAt(i) - '0' : 0;
int y = j >= 0 ? num2.charAt(j) - '0' : 0;
int result = x + y + add;
//result模10即为位数上的数
ans.append(result % 10);
//add/10即为进位数
add = result / 10;
i--;
j--;
}
// 计算完以后的答案需要翻转过来
ans.reverse();
return ans.toString();
}
11.字符串的全排列
输入一个字符串,打印出该字符串中字符的所有排列,不能有重复元素
//回溯——递归
//时间 44.53
//空间 56.89
public String[] permutation_2(String s){
char[] arr = s.toCharArray();
//去重
Set<String> res=new HashSet<>();
allPerm(arr,0,arr.length - 1,res);
String[] ans=new String[res.size()];
int i=0;
for(String str:res) ans[i++]=str;
return ans;
}
public void allPerm(char[] arr,int left,int end,Set<String> res){
if(arr == null || arr.length == 0){
// 异常情况
return;
}
if(left == end){
res.add(String.valueOf(arr));
return;
}
for(int i = left; i <= end;i++){
swap(arr,left,i);
allPerm(arr,left + 1,end,res);
//回溯至交换前的样子
swap(arr,left,i);
}
}
public void swap(char[] arr,int i,int j){
char temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
//回溯法
//时间 93.26
//空间 25.46
public String[] permutation_1(String s) {
char[] arr = s.toCharArray();
List<String> res = new LinkedList<>();
dfs(arr,0,res);
return res.toArray(new String[res.size()]);
}
public void dfs( char[] arr,int curIndex,List<String> res) {
if(curIndex == arr.length - 1) {
res.add(String.valueOf(arr)); // 添加排列方案
return;
}
//Set判断是否有重复字符
HashSet<Character> set = new HashSet<>();
int length = arr.length;
for(int i = curIndex; i <= length - 1; i++) {
if(set.contains(arr[i])) continue; // 重复,因此剪枝
set.add(arr[i]);
//先固定第i为
swap(arr,i, curIndex); // 交换,将 c[i] 固定在第 x 位
dfs(arr, curIndex+ 1,res); // 开启固定第 x + 1 位字符
swap(arr,i, curIndex); // 恢复交换
}
}
public void swap(char[] arr,int a, int b) {
char tmp = arr[a];
arr[a] = arr[b];
arr[b] = tmp;
}