[LeetCode] 767. Reorganize String

Given a string S, check if the letters can be rearranged so that two characters that are adjacent to each other are not the same.

If possible, output any possible result.  If not possible, return the empty string.

Example 1:

Input: S = "aab"
Output: "aba"

Example 2:

Input: S = "aaab"
Output: ""

Note:

  • S will consist of lowercase letters and have length in range [1, 500].

题意:给定一个字符串(只含有小写字母),把他们重新组合排序,是否能排出 每相邻两个字母不同的字符串;

只要判断出现频率最大的那个频次是否小于等于整个的一半,奇数则+1;

比方说 aba,a出现2次小于等于 3/2 + 1, abababacacada,a出现是整个的一半,满足这个条件,那么它一定能排出,反之不符合这个条件,直接返回 “” ;

接下来就是怎么排的问题,

采用大根堆(优先队列),每次出最大出现次数的那两个,然后给他们的次数-1,当他们的次数不为0时就再插回优先队列中

 1  // 建立一个特殊的数据结构,方便使用
 2     // 同时实现Comparable,为了方便比较
 3     class pot implements Comparable<pot>{
 4         char key;
 5         int val;
 6         pot(char key, int val) {
 7             this.key = key;
 8             this.val = val;
 9         }
10         @Override
11         public int compareTo(pot o) {
12             if (this.val < o.val)
13                 return 1;
14             else if (this.val == o.val)
15                 if (this.key < o.key)
16                     return 1;
17                 else if (this.key == o.key)
18                     return 0;
19             return -1;
20         }
21     }
22     public String reorganizeString(String S) {
23         int ln = S.length();
24         if (ln <= 2)
25             return S;
26         // 先找出最大的那个,因为最大只有26个字母,我们可以把每个字母出现的次数记录下来
27         int [] arr = new int [26];
28         for (int i = 0; i < ln; i++)
29             arr[S.charAt(i) - 'a'] ++;
30         int max = 0;
31         int maxIndex = 0;
32         for (int i = 0; i < 26; i++) {
33             if (max < arr[i]) {
34                 max = arr[i];
35                 maxIndex = i;
36             }
37         }
38         if ((ln%2 == 0 && max > ln/2) || (ln%2 != 0 && max > ln/2 + 1))
39             return "";
40         String str = "";
41         // 到这,我们已经确定是可以排的了
42         
43         PriorityQueue<pot> pots = new PriorityQueue<>();
44         for (int i = 0; i < 26; i++) {
45             if (arr[i] != 0)
46                 pots.add(new pot((char)(i + 'a'), arr[i]));
47         }
48         pot pt1;
49         pot pt2;
50         while (!pots.isEmpty()) {
51             pt1 = pots.poll();
52             str += pt1.key;
53             pt1.val --;
54             if (!pots.isEmpty()) {
55                 pt2 = pots.poll();
56                 str += pt2.key;
57                 pt2.val --;
58                 if (pt1.val != 0)
59                     pots.add(pt1);
60                 if (pt2.val != 0)
61                     pots.add(pt2);
62             }
63         }
64         return str;
65     }
66 }

 

posted @ 2018-09-05 22:23  C`Moriarty  阅读(287)  评论(0编辑  收藏  举报
/* 鼠标点击求赞文字特效 */ /*鼠标跟随效果*/