October 08, 2018

How to check whether the strings are anagram or not

/**
 * An anagram of a string is another string that contains same characters, only the order of characters can be different.
 */
package com.belazy.algorithm;

import java.util.Arrays;

/**
 * @author rahul eswar
 *
 */
public class Anagrams {

/**
* @param args
*/
public static void main(String[] args) {
String s = "SAVE";
String d = "VASE";
Anagrams anagram = new Anagrams();
boolean b = anagram.isAnagram(s,d);
System.out.println(" answer is "+b);
boolean j = anagram.isAnagram2(s,d);
System.out.println(" answer is "+b);
}

private boolean isAnagram2(String s, String d) {
char[] c = s.toCharArray();
char[] e = d.toCharArray();
Arrays.sort(c);
Arrays.sort(e);
System.out.println(c);
System.out.println(e);
return Arrays.equals(c, e);
}

private boolean isAnagram(String s, String d) {
boolean isAnagram = false;
if(s.length()!=d.length()){
System.out.println(" Not ");
}else{
for(int i =0; i<s.length();i++){
char c = s.charAt(i);
System.out.print(" comapring "+c+" & "+d);
if(d.contains(String.valueOf(c))){
System.out.println("--> OK");
isAnagram = true;
continue;
}else{
System.out.println("--> NOT OK");
isAnagram = false;
break;
}
}
}
return isAnagram ;
}
}


Output

 comapring S & VASE--> OK
 comapring A & VASE--> OK
 comapring V & VASE--> OK
 comapring E & VASE--> OK
 answer is true
AESV
AESV
 answer is true



No comments:

Post a Comment

Your feedback may help others !!!

Facebook comments