-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReorganizeString.java
More file actions
60 lines (59 loc) · 2.21 KB
/
ReorganizeString.java
File metadata and controls
60 lines (59 loc) · 2.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package leetcode.string;
/**
* @ClassName ReorganizeString
* @Description 重构字符串 https://leetcode-cn.com/problems/reorganize-string/
* @Author changxuan
* @Date 2020/11/30 下午8:18
**/
public class ReorganizeString {
public static void main(String[] args) {
char[] a = new char[4];
System.out.println(a.length);
int cx = 0;
System.out.println(cx++ == 1);
}
public String reorganizeString(String S) {
//把字符串S转化为字符数组
char[] alphabetArr = S.toCharArray();
//记录每个字符出现的次数
int[] alphabetCount = new int[26];
//字符串的长度
int length = S.length();
//统计每个字符出现的次数
for (int i = 0; i < length; i++) {
alphabetCount[alphabetArr[i] - 'a']++;
}
int max = 0, alphabet = 0, threshold = (length + 1) >> 1;
//找出出现次数最多的那个字符
for (int i = 0; i < alphabetCount.length; i++) {
if (alphabetCount[i] > max) {
max = alphabetCount[i];
alphabet = i;
//如果出现次数最多的那个字符的数量大于阈值,说明他不能使得
// 两相邻的字符不同,直接返回空字符串即可
if (max > threshold)
return "";
}
}
//到这一步说明他可以使得两相邻的字符不同,我们随便返回一个结果,res就是返回
//结果的数组形式,最后会再转化为字符串的
char[] res = new char[length];
int index = 0;
//先把出现次数最多的字符存储在数组下标为偶数的位置上
while (alphabetCount[alphabet]-- > 0) {
res[index] = (char) (alphabet + 'a');
index += 2;
}
//然后再把剩下的字符存储在其他位置上
for (int i = 0; i < alphabetCount.length; i++) {
while (alphabetCount[i]-- > 0) {
if (index >= res.length) {
index = 1;
}
res[index] = (char) (i + 'a');
index += 2;
}
}
return new String(res);
}
}