首页 > 其他 > 详细

LeetCode 767. Reorganize String

时间:2019-12-05 10:23:46      阅读:66      评论:0      收藏:0      [点我收藏+]

原题链接在这里:https://leetcode.com/problems/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].

题解:

In order to makie adjacent chars different from each other, we need to find the most frequent char and arrange it first.

If the frequency of most frequent char is > (S.length()+1)/2, that means there is no way to arrange without putting 2 most frequent char adjacent, return "".

Otherwise, arrange most prequent char first starting from index 0, index += 2.

After this, place the rest chars starting from current index and when index hit the end, reset it to 1.

Time Complexity: O(n). n =S.length.

Space: O(n).

AC Java:

 1 class Solution {
 2     public String reorganizeString(String S) {
 3         if(S == null || S.length() == 0){
 4             return S;
 5         }
 6         
 7         int n = S.length();
 8         int [] map = new int[26];
 9         char maxChar = ‘a‘;
10         int maxCount = 0;
11         for(char c : S.toCharArray()){
12             map[c-‘a‘]++;
13             if(map[c-‘a‘] > maxCount){
14                 maxCount = map[c-‘a‘];
15                 maxChar = c;
16             }
17         }
18         
19         if(maxCount > (n+1)/2){
20             return "";
21         }
22         
23         char [] res = new char[n];
24         int i = 0;
25         while(map[maxChar-‘a‘] > 0){
26             res[i] = maxChar;
27             map[maxChar-‘a‘]--;
28             i+=2;
29         }
30         
31         for(int j = 0; j<26; j++){
32             while(map[j]>0){
33                 if(i>=n){
34                     i = 1;
35                 }
36                 
37                 res[i] = (char)(‘a‘+j);
38                 map[j]--;
39                 i+=2;
40                 
41             }
42         }
43         
44         return new String(res);
45     }
46 }

 

LeetCode 767. Reorganize String

原文:https://www.cnblogs.com/Dylan-Java-NYC/p/11986902.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!