Last active
September 24, 2020 07:53
-
-
Save priyankshah217/9c522b9c5b072a2dca0aeb616d94f115 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
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
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
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