-
-
Notifications
You must be signed in to change notification settings - Fork 110
/
SherlockandAnagrams.java
41 lines (40 loc) · 1.22 KB
/
SherlockandAnagrams.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String args[]) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
while(t--!=0){
int count = 0;
String s = br.readLine();
int n = s.length();
String s1,s2;
for(int i=1;i<=n;i++){
for(int j=0;j+i<=n;j++){
s1=s.substring(j,j+i);
for(int k=j+1;k+i<=n;k++){
s2=s.substring(k,k+i);
if(anagram(s1,s2))
count++;
}
}
}
System.out.println(count);
}
}
public static boolean anagram(String s1,String s2){
if(s1.length()!=s2.length())
return false;
char[] c1 = s1.toCharArray();
for(char c : c1){
int index = s2.indexOf(c);
if(index!=-1){
s2 = s2.substring(0,index)+s2.substring(index+1,s2.length());
}
else{
return false;
}
}
return s2.isEmpty();
}
}