标签:
Given a non-empty string str and an integer k, rearrange the string such that the same characters are at least distance k from each other.
All input strings are given in lowercase letters. If it is not possible to rearrange the string, return an empty string ""
.
Example 1:
str = "aabbcc", k = 3 Result: "abcabc" The same letters are at least distance 3 from each other.
Example 2:
str = "aaabc", k = 3 Answer: "" It is not possible to rearrange the string.
Example 3:
str = "aaadbbcc", k = 2 Answer: "abacabcd" Another possible answer is: "abcabcda" The same letters are at least distance 2 from each other.
Credits:
Special thanks to @elmirap for adding this problem and creating all test cases.
import java.util.Map.Entry; public class Solution { public String rearrangeString(String str, int k) { if (str.isEmpty() || k<0) return ""; if (k==0) return str; HashMap<Character,Integer> charMap = new HashMap<Character,Integer>(); for (char c : str.toCharArray()){ charMap.put(c,charMap.getOrDefault(c,0)+1); } char[] chars = new char[charMap.size()]; int[] charCount = new int[charMap.size()]; int[] valid = new int[charMap.size()]; int index = 0; for (Entry entry : charMap.entrySet()){ char c = (char) entry.getKey(); int count = (int) entry.getValue(); chars[index] = c; charCount[index++] = count; } StringBuilder builder = new StringBuilder(); int nextInd = 0; int nextChar = getNextChar(charCount,valid,nextInd); while (nextChar!=-1){ builder.append(chars[nextChar]); charCount[nextChar]--; valid[nextChar] = (nextInd++) + k; nextChar = getNextChar(charCount,valid,nextInd); } if (builder.length()!=str.length()) return ""; return builder.toString(); } public int getNextChar(int[] charCount, int[] valid, int nextInd){ int maxCount = 0; int index = -1; for (int i=0;i<charCount.length;i++) if (valid[i]<=nextInd && charCount[i]>maxCount){ maxCount = charCount[i]; index = i; } return index; } }
Solution 2:
import java.util.Map.Entry; public class Solution { public String rearrangeString(String str, int k) { if (str.isEmpty() || k<0) return ""; if (k==0) return str; int[] charCount = new int[26]; int[] valid = new int[26]; Arrays.fill(valid,-1); for (char c : str.toCharArray()){ charCount[c-‘a‘]++; } for (int i=0;i<26;i++) if (charCount[i]>0){ valid[i] = 0; } StringBuilder builder = new StringBuilder(); int nextInd = 0; int nextChar = getNextChar(charCount,valid,nextInd); while (nextChar!=-1){ builder.append((char)(nextChar+‘a‘)); charCount[nextChar]--; valid[nextChar] = (nextInd++) + k; nextChar = getNextChar(charCount,valid,nextInd); } if (builder.length()!=str.length()) return ""; return builder.toString(); } public int getNextChar(int[] charCount, int[] valid, int nextInd){ int maxCount = 0; int index = -1; for (int i=0;i<charCount.length;i++) if (valid[i]<=nextInd && charCount[i]>maxCount){ maxCount = charCount[i]; index = i; } return index; } }
LeetCode-Rearrange String k Distance Apart
标签:
原文地址:http://www.cnblogs.com/lishiblog/p/5856198.html