Skip to content

Instantly share code, notes, and snippets.

@priyankshah217
Last active September 24, 2020 07:53
Show Gist options
  • Save priyankshah217/9c522b9c5b072a2dca0aeb616d94f115 to your computer and use it in GitHub Desktop.
Save priyankshah217/9c522b9c5b072a2dca0aeb616d94f115 to your computer and use it in GitHub Desktop.
public class FindAllPermutationsInGivenString {
public static void main(String[] args) {
FindAllPermutationsInGivenString obj = new FindAllPermutationsInGivenString();
String inputText = "abcdefcabdpqrbcaz";
String inputWord = "dbca";
List<Integer> listOfStartingIndex = obj.getListOfStartingIndex(inputText, inputWord);
listOfStartingIndex.forEach(System.out::println);
}
private List<Integer> getListOfStartingIndex(String inputText, String inputWord) {
List<Integer> listOfStartingIndex = new ArrayList<>();
char[] alphabetArrayForWord = new char[26];
for (char ch : inputWord.toCharArray()) {
alphabetArrayForWord[ch - 'a']++;
}
int index = 0;
int right = inputWord.length();
char[] alphabetArrayForText = new char[26];
while (index < inputText.length()) {
if (index < inputWord.length()) {
char ch = inputText.charAt(index);
alphabetArrayForText[ch - 'a']++;
} else {
char ch = inputText.charAt(index);
alphabetArrayForText[ch - 'a']++;
ch = inputText.charAt(index - right);
alphabetArrayForText[ch - 'a']--;
}
if (Arrays.hashCode(alphabetArrayForWord) == Arrays.hashCode(alphabetArrayForText)) {
listOfStartingIndex.add(index - right + 1);
}
index++;
}
return listOfStartingIndex;
}
}
@AliMsayleb
Copy link

I implemented something very similar but instead of comparing the hash of two arrays every time i kept a count of the differences, and whenever the differences count is 0 i added the position. Check it out here (But using PHP) https://ide.geeksforgeeks.org/mc8FoYJcJp

@AliMsayleb
Copy link

I implemented something very similar but instead of comparing the hash of two arrays every time i kept a count of the differences, and whenever the differences count is 0 i added the position. Check it out here (But using PHP) https://ide.geeksforgeeks.org/mc8FoYJcJp

Sliding window technique

@priyankshah217
Copy link
Author

Even my current solution also based on slidingwindow..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment