算法_Java

发布时间 2023-12-19 22:23:51作者: Espre-sso

KMP

作用

快速找到串a中存在的串b

思想

前缀 && 后缀相同

解法

  1. 对小串b维护一个数组,数组记录以该位置为后缀结尾,最长的匹配前缀下标。
    做法,i后缀结尾1->len-1,j前缀结尾初始为0,一旦ij的值匹配,i++,j++。不匹配,j循环回退KMP[j-1],i不++。
  2. 遍历大串a时,不匹配则小串下标->KMP[n-1]的值。

Java_List集合、字符数组、字符串互相转换

List->字符数组:遍历赋值 or Java8后引入的stream
int[] arr = list.stream().toArray(int[] ::new);
String也可以与Integer强转
String s = String.valueOf(i);
int i = Integer.valueOf(s);
String <-> charArray转换
char[] chars = s.toCharArray();
String s = String.valueOf(chars);
字符串数组 <-> 字符串
StringBuffer sb = new StringBuffer();
for(int i=0 ; i<arr.length ; i++){
sb.append(arr[i]);
}
String sb1 = sb.toString():

java_分割字符串

String[] arr = str.split("");

Deque双端队列

常用方法:addFirstpollLast
使用:Deque<Integer> dq = new LinkedList<>();

PriorityQueue优先级队列

点击查看代码
PriorityQueue<Integer> pq = new PriorityQueue<>(new Comparator<Integer>(){
  public int compare(Integer a,Integer b){
    return b-a;//此时是大根堆,默认是小根堆
  }
});

使用:
增 offer
删 poll

递归

  1. 确定递归函数的参数和返回值。
  2. 确定终止条件。
  3. 确定单层递归的逻辑。

二叉树

深度:到根节点的距离。(根节点深度是1)
高度,到叶子节点的距离。(叶子节点高度是1)

int_最小值

Integer.MIN_VALUE

java_递归

java递归传参-引用类型传的是地址拷贝,如果要在递归过程中保留某些中间状态值,最好new一个新对象存储这些值,不要直接用函数的参数。

Set的初始化-匿名内部类、实例初始化块

点击查看代码
    	Map<Character,Set<Character>> map;
        map = new HashMap<>();
        map.put('2',new HashSet<Character>(){{
            add('a');
            add('b');
            add('c');
        }});
        map.put('3',new HashSet<Character>(){{
            add('d');
            add('e');
            add('f');
        }});

bufferpool

java 乘方

double ans = Math.pow(2,5);
int ans = (int)Math.pow(2,5);
默认返回double值

二叉树

前序:求深度,层层向下遍历,不返回结果。
后序遍历:求高度,因为返回递归结果。

java_绝对值

int num=Math.abs(-5);

字符串拼接

+

开方

double ans = Math.sqrt(9);
Math.pow(9,0.5);

字符->数字

int a=c-'0';

判断字符是数字还是字母

Character.isDigit(c);
Character.isLetter(c);

判断字符串值相等

s1.equals(s2);

java_截取数组

System.arraycopy(originalArray, startIndex, new Array, 0, length);

java_Set

想获取set中的元素,只能遍历!
不支持下标!