Skip to content

Commit 067d895

Browse files
committed
Added program to count occurence of an anagram
1 parent e85890d commit 067d895

File tree

2 files changed

+40
-2
lines changed

2 files changed

+40
-2
lines changed

Diff for: java/strings/Anagram.java

-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
11
public class Anagram {
2-
3-
42
/*
53
* Input: "Keep", "Peek"
64
* Output: false

Diff for: java/strings/countAnagrams.java

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
// Given a word and a text, return the count of occurences of anagrams of the word in the text(For eg: anagrams of word for are for, ofr, rof etc.)
2+
// For example :
3+
// Input: forxxorfxdofr
4+
// for
5+
// Output: 3
6+
7+
import java.util.*;
8+
import java.io.*;
9+
10+
class Anagrams{
11+
final static int MAX = 256;
12+
// to check if two strings are equal.
13+
static boolean isAnagram(String s1, String s2){
14+
char[] c1 = s1.toCharArray();
15+
char[] c2 = s2.toCharArray();
16+
Arrays.sort(c1);
17+
Arrays.sort(c2);
18+
if(Arrays.equals(c1, c2))
19+
return true;
20+
return false;
21+
}
22+
23+
static int countAnagrams(String text, String word){
24+
int N = text.length();
25+
int n = word.length();
26+
int res = 0;
27+
for(int i=0;i<=N-n;i++){
28+
String s = text.substring(i, i+n);
29+
if(isAnagram(word, s))
30+
res++;
31+
}
32+
return res;
33+
}
34+
35+
public static void main(String args[]){
36+
String text = "forxxorfxdofr";
37+
String word = "for";
38+
System.out.println(countAnagrams(text, word));
39+
}
40+
}

0 commit comments

Comments
 (0)