基本定义
字符:String
是由一系列字符组成的,字符的类型是char
,可能有2^16
个值。
不可变性:String
对象是不可变的,因此可以将它们用于赋值语句,作为函数的对数或是返回值,而不用担心它们的值会发生变化。
索引:我们常用的操作就是从某个字符串中提取一个特定的字符,即Java
的String
类的charAt()
方法,就好像字符串是保存在一个char[]
数组中一样。
长度:在Java
中,String
类型的length()
方法实现了获取字符串的长度的操作。同样,我们也希望length()
方法能够在常数时间内完成。
子字符串:Java
的substring()
方法实现了提取特定的子字符串的操作。我们也希望这个方法能够在常数时间内完成。
在Java中表示字符串的两种方法
操作 | 字符数组 | Java字符串 |
---|---|---|
声明 | char[] a | String s |
根据索引访问字符 | a[i] | s.charAt(i) |
获取字符串长度 | a.length | s.length() |
表示方法转换 | a=s.toCharArray(); | s=new String(a); |
键索引计数法
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class StrKey {
private int key;
private int value;
}
package algorithm.string;
import java.util.Arrays;
import java.util.Random;
public class KeyIndexSort {
private final static int R = 256;
public static void main(String[] args) {
Random r = new Random();
StrKey[] a = new StrKey[5];
for (int i = 0; i < 5; i++) {
a[i] = StrKey.builder().key(r.nextInt(5)).value(r.nextInt(5)).build();
}
System.out.println(Arrays.toString(a));
sort(a);
System.out.println(Arrays.toString(a));
}
public static void sort(StrKey[] a) {
int N = a.length;
StrKey[] aux = new StrKey[N];
int[] count = new int[R + 1];
// 计算出现频率
for (StrKey strKey : a) count[strKey.getKey() + 1]++;
// 将频率转换为索引
for (int r = 0; r < R; r++) count[r + 1] += count[r];
// 将元素分类
for (StrKey strKey : a) {
aux[count[strKey.getKey()]++] = strKey;
}
// 回写
System.array(aux, 0, a, 0, N);
// System.array等价于下面
// for (int i = 0; i < N; i++) {
// a[i] = aux[i];
// }
}
}