Friday, 6 February 2015

Given two strings a and b, find whether any anagram of string a is a sub-string of string b

if a = xyz and b = afdgzyxksldfm then the program should return true. class StringDemo3 { static boolean checkAnagram(String s1,String s2) { int mycount[]=new int[128]; for (int i=0;i<s1.length();i++) { mycount[s1.charAt(i)]++; mycount[s2.charAt(i)]--; } for (int i=0;i<127;i++) { if(mycount[i]!=0) return false; } return true; } public static void main(String[] args) { String target="xyz"; String source="afdgzyxksldfm"; boolean flag=false; for (int i=0;i<source.length()-target.length()+1;i++) { if(checkAnagram(target,source.substring(i,i+target.length()))) { System.out.println("Anagram Found"); flag=true; break; } } if(!flag) System.out.println("Anagram Not Found"); } }

No comments:

Post a Comment