Advertisement
gelita

Anagram Pair

Feb 8th, 2020
197
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.53 KB | None | 0 0
  1.  
  2. import java.io.*;
  3. import java.util.*;
  4.  
  5. class MyCode {
  6.  
  7.    /**
  8.     *  9  Anagram Pair
  9.     *
  10.     *  Given two strings, determine if the strings are anagrams of one another.
  11.     *
  12.     *  Two words are anagrams of one another if they contain the same letters.
  13.     *
  14.     *  Parameters
  15.     *  Input: str1 {String}
  16.     *  Input: str2 {String}
  17.     *  Output: {Boolean}
  18.     *
  19.     *  Constraints
  20.     *  With N as the length of the first string, and M as the length of the second string.
  21.     *
  22.     *  Time: O(N)
  23.     *  Space: O(N)
  24.     *
  25.     *  Examples
  26.     *  "cat", "act" --> true
  27.     *  "cat", "dog" --> false
  28.     *  "racecar", "aaccrres" --> false
  29.     */
  30.  
  31.   public static void main (String[] args) {
  32.     String s1 = "cat";
  33.     String s2 = "act";
  34.     String s3 = "dog";
  35.     String s4 = "racecar";
  36.     String s5 = "aaccrres";    
  37.     System.out.println(anagramPair(s1,s3));  
  38.     }
  39.     public static Boolean anagramPair(String string1, String string2) {
  40.       //if string lengths differ --> return false
  41.       if(string1.length() != string2.length()){
  42.         return false;
  43.       }
  44.       //if both strings are empty --> return true
  45.       if(string1 == "" && string2 == ""){
  46.         return true;
  47.       }
  48.       int len = string1.length();
  49.       char[] char1 = string1.toCharArray();
  50.       char[] char2 = string2.toCharArray();
  51.       Arrays.sort(char1);
  52.       Arrays.sort(char2);
  53.       for(int i=0; i< len; i++){
  54.         if(char1[i] != char2[i]){
  55.           return false;
  56.         }
  57.       }
  58.       return true;
  59.     }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement