Java Solution,only sort...


  • 1
    public class Solution {
        public String frequencySort(String s) {
            if (s.length() < 3)
    			return s;
    		char[] ar = s.toCharArray();
    		Arrays.sort(ar);
    		String str = String.valueOf(ar);
    
    		LinkedList<String> list = getList(str);
    		
    		Collections.sort(list, new Comparator<String>() {
    
    			@Override
    			public int compare(String o1, String o2) {
    				int a = o1.length();
    				int b = o2.length();
    
    				if (a > b)
    					return -1;
    				else if (a < b)
    					return 1;
    				return 0;
    			}
    		});
    		StringBuffer sb = new StringBuffer();
    		for (String x : list)
    			sb.append(x);
    
    		return sb.toString();
    
    	}
    
    	public static LinkedList<String> getList(String str) {
    		int len = str.length();
    		char c = str.charAt(0);
    		int max = 1;
    		LinkedList<String> list = new LinkedList<String>();
    		for (int i = 1; i < len; i++) {
    
    			if (str.charAt(i) != c) {
    
    				if (list.size() == 0) {
    					list.add(str.substring(0, max));
    				} else {
    					list.add(str.substring(i - max, i));
    
    				}
    				c = str.charAt(i);
    				max = 1;
    			} else {
    				max++;
    			}
    
    		}
    
    		if (max > 1) {
    			list.add(str.substring(len - max, len));
    		} else {
    			if (list.getLast().contains(str.charAt(len - 1) + ""))
    				list.add(list.pollLast() + str.charAt(len - 1));
    			else
    				list.add(str.charAt(len - 1) + "");
    		}
    		return list;
    
    	}
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.