Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 88248f2

Browse files
committed
Anagrams in string: naive sol. done
1 parent 56f0fa2 commit 88248f2

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
package com.leetcode.strings;
2+
3+
import java.util.ArrayList;
4+
import java.util.Arrays;
5+
import java.util.List;
6+
7+
/**
8+
* Leetcode Problem: https://leetcode.com/problems/find-all-anagrams-in-a-string/
9+
*
10+
* @author rampatra
11+
* @since 2019年04月13日
12+
*/
13+
public class AnagramsInString {
14+
15+
private static List<Integer> findAllAnagramsInTextNaive(String text, String pattern) {
16+
List<Integer> indexes = new ArrayList<>();
17+
18+
int textLen = text.length();
19+
int patternLen = pattern.length();
20+
21+
char[] patternChars = pattern.toCharArray();
22+
Arrays.sort(patternChars); // takes O(m log m) time
23+
String sortedPattern = String.valueOf(patternChars);
24+
25+
String subText;
26+
char[] subTextChars;
27+
String sortedSubText;
28+
29+
for (int i = 0; i <= textLen - patternLen; i++) { // loops n-m number of times
30+
subText = text.substring(i, i + patternLen);
31+
subTextChars = subText.toCharArray();
32+
Arrays.sort(subTextChars); // sorts m number of characters, takes O(m log m)
33+
sortedSubText = String.valueOf(subTextChars);
34+
35+
if (sortedSubText.equals(sortedPattern)) { // compare m characters takes m time
36+
indexes.add(i);
37+
}
38+
}
39+
return indexes;
40+
}
41+
42+
public static void main(String[] args) {
43+
// basic use cases
44+
System.out.println(findAllAnagramsInTextNaive("cbaebabacd", "abc"));
45+
System.out.println(findAllAnagramsInTextNaive("abab", "ab"));
46+
47+
// corner cases
48+
System.out.println(findAllAnagramsInTextNaive("abab", ""));
49+
System.out.println(findAllAnagramsInTextNaive("", "ab"));
50+
System.out.println(findAllAnagramsInTextNaive("", ""));
51+
}
52+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /