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].

 改写一个字符串,使得连续的两个字符不相同
首先排除不可能构造的字符串,即有一个字符的数量超过了字符串长度的一半。
构造的方法很简单,将原本的字符串排序,然后将前一半和后一半交叉构造成新的字符串,就是答案。

但是要考虑一个特殊情况,即有一个字符的数量等于字符串长度的一半,这样的字符必须是答案的第一个字符和最后一个字符。为了解决这个问题,我的办法是改变排序的规则,即将这个数量很大的字符放在排序字符串的最前面。

class Solution {
    public String reorganizeString(String S) {
        int[] record = new int[26];
        int len = S.length();
        int spe = -1;
        for(char ch : S.toCharArray()){
        	record[ch - 'a']++;
        }
        for(int i = 0; i < 26; i++){
        	if(record[i] > (len + 1) / 2)
        		return "";
        	if(record[i] == (len + 1) / 2)
        		spe = i;
        }
        char[] chs = new char[len];
        int it = 0;
        if(spe != -1){
        	while(record[spe]-- > 0)
        		chs[it++] = (char)(spe + 'a');
        }
        for(int i = 0; i < 26; i++){
        	while(record[i]-- > 0)
        		chs[it++] = (char)(i + 'a');
        }
        
        //System.out.println(new String(chs));
        char[] res = new char[len];
        it = 0;
        
        int left = 0, right = (len + 1) / 2;
        while(right < len){
        	res[it++] = chs[left++];
        	res[it++] = chs[right++];
        }
        if(left < (len + 1) / 2)
        	res[it] = chs[left];
        String str = new String(res);
        return str;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值