重构字符串

给定一个字符串S,检查是否能重新排布其中的字母,使得两相邻的字符不同。

若可行,输出任意可行的结果。若不可行,返回空字符串。

示例 1:

输入: S = “aab”
输出: “aba”
示例 2:

输入: S = “aaab”
输出: “”
注意:

S 只包含小写字母并且长度在[1, 500]区间内。

思路:
首先,判断是否可以重构字符串,若某个字符出现的频率大于字符串长度的一半,就不能重构。
难点在于如何重构字符串使任意相同字符不重复。网上看到别人做法,构造一个类用于存放字符和字符出现的频率,然后用优先队列来解决。

 public String reorganizeString(String S) {
		  int len = S.length();
	      int[] data = new int[26];
	      for(int i=0;i<=len;i++) {
	    	  data[S.charAt(i)-'a']++;
	      }
	     PriorityQueue<NewChar> pq = new PriorityQueue<NewChar>(new Comparator<NewChar>() {

			@Override
			public int compare(NewChar o1, NewChar o2) {
				
				return o2.count-o1.count;
			}
	    	 
	     }) ;
	     
	     for(int i=0;i<26;i++) {
	    	 if(data[i]>0&&data[i]<=(len+1)/2)
	    		 pq.add(new NewChar(data[i],(char)(i+'a')));
	    	 else if(data[i]>(len+1)/2)
	    		 return "";
	    	 }
	     
	     String str="";
	     while(pq.size()>1) {
	    	 NewChar c1 = pq.poll();
	    	 NewChar c2 = pq.poll();
	    	 if(str.length()==0 || c1.letter!=str.charAt(str.length()-1)) {
	    		 str += c1.letter;
	    		 str += c2.letter;
	    	 }
	    	 if(--c1.count>0) pq.add(c1);
	    	 if(--c2.count>0) pq.add(c2);
	   
	     }
	    if(pq.size()>0)
	    	str += pq.poll().letter;
	    
	    return str;
	  }
class NewChar{
	public int count;
	public char letter;
	public NewChar(int count,char letter) {
		this.count = count;
		this.letter = letter;
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值