Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.util.*;
- class MyCode {
- /**
- * 9 Anagram Pair
- *
- * Given two strings, determine if the strings are anagrams of one another.
- *
- * Two words are anagrams of one another if they contain the same letters.
- *
- * Parameters
- * Input: str1 {String}
- * Input: str2 {String}
- * Output: {Boolean}
- *
- * Constraints
- * With N as the length of the first string, and M as the length of the second string.
- *
- * Time: O(N)
- * Space: O(N)
- *
- * Examples
- * "cat", "act" --> true
- * "cat", "dog" --> false
- * "racecar", "aaccrres" --> false
- */
- public static void main (String[] args) {
- String s1 = "cat";
- String s2 = "act";
- String s3 = "dog";
- String s4 = "racecar";
- String s5 = "aaccrres";
- System.out.println(anagramPair(s1,s3));
- }
- public static Boolean anagramPair(String string1, String string2) {
- //if string lengths differ --> return false
- if(string1.length() != string2.length()){
- return false;
- }
- //if both strings are empty --> return true
- if(string1 == "" && string2 == ""){
- return true;
- }
- int len = string1.length();
- char[] char1 = string1.toCharArray();
- char[] char2 = string2.toCharArray();
- Arrays.sort(char1);
- Arrays.sort(char2);
- for(int i=0; i< len; i++){
- if(char1[i] != char2[i]){
- return false;
- }
- }
- return true;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement