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

方法一:暴力实现,但肯定会TLE,因为字符串长度最长可以为500,500!是一个天文数字,因此肯定会TLE,但也是一种方法,程序如下所示:

class Solution {
    String s = "";
    public String reorganizeString(String S) {
        char[] ch = S.toCharArray();
        backTracingString(ch, new char[ch.length], 0, new HashSet<Integer>());
        return s;
    }
    
    public boolean backTracingString(char[] ch, char[] res, int index, Set<Integer> set){
        if (index == ch.length){
            s = new String(res);
            return true;
        }
        for (int i = 0; i < ch.length; ++ i){
            if (set.contains(i)){
                continue;
            }
            if (index > 0 && ch[i] == res[index-1]){
                continue;
            }
            res[index] = ch[i];
            set.add(i);
            if (backTracingString(ch, res, index + 1, set)){
                return true;
            }
            set.remove(i);
        }
        return false;
    }
}

方法二:待补充

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值