您的位置:首页 > 其它

LeetCode 358. Rearrange String k Distance Apart(字符间隔)

2016-06-15 03:27 288 查看
原题网址:https://leetcode.com/problems/rearrange-string-k-distance-apart/

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.

方法:根据出现频率将字母从大到小排列,以k为间隔进行重排。

public class Solution {
public String rearrangeString(String str, int k) {
if (k <= 0) return str;
int[] f = new int[26];
char[] sa = str.toCharArray();
for(char c: sa) f[c-'a'] ++;
int r = sa.length / k;
int m = sa.length % k;
int c = 0;
for(int g: f) {
if (g-r>1) return "";
if (g-r==1) c ++;
}
if (c>m) return "";
Integer[] pos = new Integer[26];
for(int i=0; i<pos.length; i++) pos[i] = i;
Arrays.sort(pos, new Comparator<Integer>() {
@Override
public int compare(Integer i1, Integer i2) {
return f[pos[i2]] - f[pos[i1]];
}
});
char[] result = new char[sa.length];
for(int i=0, j=0, p=0; i<sa.length; i++) {
result[j] = (char)(pos[p]+'a');
if (-- f[pos[p]] == 0) p ++;
j += k;
if (j >= sa.length) {
j %= k;
j ++;
}
}
return new String(result);
}
}

方法二:最多允许有str.length() % k个冗余的字符,所以可以不排序,O(N)时间复杂度。

public class Solution {
public String rearrangeString(String str, int k) {
if (str == null || str.length() <= 1 || k <= 0) return str;
char[] sa = str.toCharArray();
int[] frequency = new int[26];
for(char ch : sa) {
frequency[ch - 'a'] ++;
}
int bucketSize = sa.length / k;
int remainSize = sa.length % k;
int[] remain = new int[remainSize];
int count = 0;
for(int i = 0; i < frequency.length; i++) {
if (frequency[i] > bucketSize + 1) return "";
if (frequency[i] > bucketSize && count >= remainSize) return "";
if (frequency[i] > bucketSize) remain[count++] = i;
}

int offset = 0, j = 0;
for(int i = 0; i < count; i++) {
while (frequency[remain[i]] > 0) {
frequency[remain[i]] --;
sa[j] = (char)('a' + remain[i]);
j += k;
if (j >= sa.length) {
offset ++;
j = offset;
}
}
}

for(int i = 0; i < 26; i ++) {
while (frequency[i] > 0) {
frequency[i] --;
sa[j] = (char)('a' + i);
j += k;
if (j >= sa.length) {
offset ++;
j = offset;
}
}
}
return new String(sa);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode