Find All Permutation of a given String in Easy Way

import java.util.HashSet;

public class StringPermutation {

public static void main(String[] args){
HashSet<String> output = new HashSet<>();
String input = "ABC";
doPermutation(input, output);
System.out.println(output);
}

private static void doPermutation(String input, HashSet<String> set) {
HashSet<String> inputList = new HashSet<>();
inputList.add(input);
for(int i=0; i<input.length()-1; i++){
int finalI = i;
inputList.forEach((k) -> {
for (int j = finalI; j < input.length(); j++) {
set.add(swap(k, finalI, j));
}
});
inputList = (HashSet<String>) set.clone();
}
}

private static String swap(String str, int firstIndex, int secondIndex) {
StringBuilder sb = new StringBuilder(str);
sb.setCharAt(firstIndex, str.charAt(secondIndex));
sb.setCharAt(secondIndex, str.charAt(firstIndex));
return sb.toString();
}


}

--

--

--

Principal Software Engineer , Mobile Engineering

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Leet Code’s 30 Day Coding Challenge

Fix — divide(java.math.BigDecimal,int) in java.math.BigDecimal has been deprecated — And WHY

The 12 Worst Types Ironman Coach Accounts You Follow On Twitter

Critical Review of BellMan-Ford Algo

Apache Spark Structured Streaming

AR technology for Android — Part 3: ARCore SDK

Starting with HILT

Singly, Doubly and Circularly Linked Lists(SLL, DLL, SCLL, DCLL) — Data Structures

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Amit Gupta

Amit Gupta

Principal Software Engineer , Mobile Engineering

More from Medium

Spider-Man: No Way Home review —

HackerRank: Sum vs XOR

Programming 24/1/22

What is Object Oriented Programing?