4
특정 문자를 별표로 대체해야하는 단어가 있는데이 대체 단어를 모두 가져와야합니다. 예를 들면. 그 결과로이 목록을 얻을 수 있지만특정 문자를 모두 바꾸고 모든 변형을 적용하십시오.
String word = telephone;
: 나는에 별표 (*)로 문자 'E'를 대체 할 자바에서이 작업을 수행하는 빠른 방법은
List of words = [t*lephone, tel*phone, telephon*, t*l*phone, t*lephon*, tel*phon*, t*l*phon*];
있습니까? 그래서
public static Set<String> getPermutations(final String string, final char c) {
final Set<String> permutations = new HashSet<>();
final int indexofChar = string.indexOf(c);
if (indexofChar <= 0) {
permutations.add(string);
} else {
final String firstPart = string.substring(0, indexofChar + 1);
final String firstPartReplaced = firstPart.replace(c, '*');
final String lastPart = string.substring(indexofChar + 1, string.length());
for (final String lastPartPerm : getPermutations(lastPart, c)) {
permutations.add(firstPart + lastPartPerm);
permutations.add(firstPartReplaced + lastPartPerm);
}
}
return permutations;
}
그것은 출력에 원래 String
을 추가 : 다음 코드는 재귀 적 방법으로 그렇게 할 것입니다
나는 그렇게 생각하지 않는다. 간단한 재귀 알고리즘 (DFS)을하는 것이 좋습니다. – Martinsos