【发布时间】:2017-11-12 07:41:35
【问题描述】:
需要编写一个算法以按字典顺序在给定索引处查找给定字符串的 Anagram。例如:
考虑一个字符串:ABC,那么所有字谜都按排序顺序排列:ABC ACB BAC BCA CAB CBA。因此,对于 索引 5 的值是:CAB。此外,考虑 重复 的情况,例如 AADFS anagram 将是索引 32 处的 DFASA
为此,我编写了 Algo,但我认为应该有比这更简单的东西。
import java.util.*;
public class Anagram {
static class Word {
Character c;
int count;
Word(Character c, int count) {
this.c = c;
this.count = count;
}
}
public static void main(String[] args) {
System.out.println(findAnagram("aadfs", 32));
}
private static String findAnagram(String word, int index) {
// starting with 0 that's y.
index--;
char[] array = word.toCharArray();
List<Character> chars = new ArrayList<>();
for (int i = 0; i < array.length; i++) {
chars.add(array[i]);
}
// Sort List
Collections.sort(chars);
// To maintain duplicates
List<Word> words = new ArrayList<>();
Character temp = chars.get(0);
int count = 1;
int total = chars.size();
for (int i = 1; i < chars.size(); i++) {
if (temp == chars.get(i)) {
count++;
} else {
words.add(new Word(temp, count));
count = 1;
temp = chars.get(i);
}
}
words.add(new Word(temp, count));
String anagram = "";
while (index > 0) {
Word selectedWord = null;
// find best index
int value = 0;
for (int i = 0; i < words.size(); i++) {
int com = combination(words, i, total);
if (index < value + com) {
index -= value;
if (words.get(i).count == 1) {
selectedWord = words.remove(i);
} else {
words.get(i).count--;
selectedWord = words.get(i);
}
break;
}
value += com;
}
anagram += selectedWord.c;
total--;
}
// put remaining in series
for (int i = 0; i < words.size(); i++) {
for (int j = 0; j < words.get(i).count; j++) {
anagram += words.get(i).c;
}
}
return anagram;
}
private static int combination(List<Word> words, int index, int total) {
int value = permutation(total - 1);
for (int i = 0; i < words.size(); i++) {
if (i == index) {
int v = words.get(i).count - 1;
if (v > 0) {
value /= permutation(v);
}
} else {
value /= permutation(words.get(i).count);
}
}
return value;
}
private static int permutation(int i) {
if (i == 1) {
return 1;
}
return i * permutation(i - 1);
}
}
谁能帮我解决不太复杂的逻辑。
【问题讨论】:
-
好问题。没有想太多,你的代码对我来说看起来并不过分复杂。
-
我遇到了同样的问题。这是editorial 的链接。希望这会有所帮助。
-
使用带有“排列”和“排名”的搜索功能。
标签: java algorithm sorting optimization anagram