Leetcode——767. Reorganize String

题目原址

https://leetcode.com/problems/reorganize-string/description/

题目描述

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

解题思路

给定一个字符串,挪动给定的字符串中字符的位置,使得返回的字符串需要相邻的两个字符不能相同。

思路:

  • 首先将给定的字符串按照字符存储在一个int的数组中,数组的下标为字符串中字符-‘a’,所以该数组将相同的字符的个数存储在数组中。
  • 利用maxLength获得数组中元素最大的值,即字符串中重复出现的字符最多的字符个数,如果该个数 * 2 - 1大于字符串的长度,就说明相同的字符太多,其他字符已经不能将相同字符分割开
  • 将字符串中的字符按照奇数偶数放在新建的char数组中。将相同的字符个数小于字符串长度的一半的字符放在奇数下标位置,否则放在偶数下标位置。注意这里需要判断奇数位置是否大于字符串长度

AC代码

class Solution {
    public String reorganizeString(String S) {
        int[] arr = new int[26];
        int lenght = S.length();
        if(S.length() == 1) return S;
        char[] ret = new char[lenght];
        int maxLength = 0;
        for(char a: S.toCharArray()) {
            if(maxLength < ++arr[a - 'a'])
                maxLength = arr[a - 'a'];
        }
        if(maxLength * 2 - 1 > S.length())
            return "";
        int odd = 0, even = 1;
        for(int i = 0; i < 26; i++) {

                while(arr[i] > 0 && arr[i] < lenght / 2 + 1 && even < lenght) {
                    ret[even] = (char)(i + 'a');
                    arr[i] --;
                    even += 2;
                }
                while(arr[i] > 0) {
                    ret[odd] = (char)(i + 'a');
                    arr[i] --;
                    odd += 2;
                }
        }

        return new String(ret);        
    }
}

感谢

https://leetcode.com/problems/reorganize-string/discuss/113429/Java-O(N)-simple-solution

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值