Tuesday, May 14, 2019

how do you check whether two strings are anagram to each other?

Problem statement:
Given two Strings S1 and S2. You have to check whether these two strings are anagram to each other?
  1. import java.util.ArrayList;
  2. import java.util.Arrays;
  3. public class Anagram {
  4.     public static void main(String[] args) {
  5.         String S1 = "LISTEN";
  6.         String S2 = "SILENT";
  7.         if (areAnagram(S1, S2)) {
  8.             System.out.println("Anagram");
  9.         } else {
  10.             System.out.println("Not an Anagram");
  11.         }
  12.     }
  13.     static boolean areAnagram(String s1, String s2) {
  14.         char c1[] = s1.toCharArray();
  15.         char c2[] = s2.toCharArray();
  16.         int n1 = c1.length;
  17.         int n2 = c2.length;
  18.         if (n1 != n2)
  19.             return false;        
  20.         Arrays.sort(c1);
  21.         Arrays.sort(c2);        
  22.         for (int i = 0; i < n1; i++)
  23.             if (c1[i] != c2[i])
  24.                 return false;
  25.         return true;
  26.     }
  27. }
Output: 
Anagram

No comments:

Post a Comment

Blueprint for self-improvement

To learn faster: Make the process fun To understand yourself : Write To understand the world better : Read To build deeper connection : Lis...