Problem statement:
Given two Strings S1 and S2. You have to check whether these two strings are anagram to each other?
Given two Strings S1 and S2. You have to check whether these two strings are anagram to each other?
- import java.util.ArrayList;
- import java.util.Arrays;
- public class Anagram {
- public static void main(String[] args) {
- String S1 = "LISTEN";
- String S2 = "SILENT";
- if (areAnagram(S1, S2)) {
- System.out.println("Anagram");
- } else {
- System.out.println("Not an Anagram");
- }
- }
- static boolean areAnagram(String s1, String s2) {
- char c1[] = s1.toCharArray();
- char c2[] = s2.toCharArray();
- int n1 = c1.length;
- int n2 = c2.length;
- if (n1 != n2)
- return false;
- Arrays.sort(c1);
- Arrays.sort(c2);
- for (int i = 0; i < n1; i++)
- if (c1[i] != c2[i])
- return false;
- return true;
- }
- }
Output:
Anagram
No comments:
Post a Comment