<String> 161 358

161. One Edit Distance

1. The difference in length of the two strings is greater than 1, the direct return False.

2. The difference in length of the two strings is equal to 1, the length of a character string is removed, and the remaining short string should be the same.

3. The difference in length of the two strings is equal to 0, the character strings corresponding to only two positions with one exception.

 

class Solution {
    public boolean isOneEditDistance(String s, String t) {
        for(int i = 0; i < Math.min(s.length(), t.length()); i++){
            if(s.charAt(i) != t.charAt(i)){
                if(s.length() == t.length()) return s.substring(i + 1).equals(t.substring(i + 1));
                if(s.length() < t.length()) return s.substring(i).equals(t.substring(i + 1));
                else return s.substring(i + 1).equals(t.substring(i));
            }
        }
        return Math.abs(s.length() - t.length()) == 1;
    }
}

358. Rearrange String k Distance Apart

class Solution {
    public String rearrangeString(String s, int k) {
        if(k == 0 || s.length() < k) return s;
        int[] map = new int[26];
        for(char c : s.toCharArray()){
            map[c - 'a']++;
        }
        
        StringBuilder sb = new StringBuilder();
        PriorityQueue<int[]> heap = new PriorityQueue<>(
            (a, b) -> a[1] == b[1] ? a[0] - b[0] : b[1] - a[1]);
        for(int i = 0; i < 26 ; i++){
            if(map[i] > 0){
                heap.offer(new int[]{i, map[i]});
            }
        }
        
        while(!heap.isEmpty()){
            List<Integer> list = new ArrayList<>();
            for(int i = 0; i < k; i++){
                int[] cur = heap.poll();
                sb.append((char)(cur[0] + 'a'));
                list.add(cur[0]);
                
                if(heap.size() == 0){
                    if(i != k - 1 && sb.length() != s.length()) return "";
                    break;
                }
            }
            
            for(int i : list){
                if(--map[i] > 0){
                    heap.offer(new int[]{i, map[i]});
                }
            }
        }
        return sb.toString();
    }
}

Guess you like

Origin www.cnblogs.com/Afei-1123/p/12075041.html