Created
July 26, 2018 19:19
-
-
Save AbdullahMagat/1c2d64668539daad3885f39a09cb4136 to your computer and use it in GitHub Desktop.
Hackerrank Java Anagrams Solution
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Scanner; | |
public class Solution { | |
static boolean isAnagram(String a, String b) { | |
// // once you declare a.toUppercase you should assign it to a. you cannot define it as just a.toUppercase... | |
// //I solved it with the long way however I could put a and b in a character array and then use Arrays.sort(arrayname). after this steps convert them to string and check if they are equel. | |
a=a.toUpperCase(); | |
b=b.toUpperCase(); | |
boolean ret = false; | |
StringBuilder c= new StringBuilder(b); | |
if(a.length()==b.length()){ | |
for(int i=0; i<a.length();i++){ | |
for(int j=0; j<c.length();j++){ | |
if(a.charAt(i)==c.charAt(j)){ | |
c.deleteCharAt(j); | |
if(i==a.length()-1 && c.length()==0){ | |
ret=true; | |
break; | |
} | |
break; | |
} | |
} | |
} | |
}return ret; | |
} | |
public static void main(String[] args) { | |
Scanner scan = new Scanner(System.in); | |
String a = scan.next(); | |
String b = scan.next(); | |
scan.close(); | |
boolean ret = isAnagram(a, b); | |
System.out.println( (ret) ? "Anagrams" : "Not Anagrams" ); | |
} | |
} |
import java.util.Scanner;
public class Solution {
static boolean isAnagram(String a, String b) {
// Complete the function
if(a.length() == b.length()){
a=a.toUpperCase();
b=b.toUpperCase();
char[] ch1 = a.toCharArray();
char[] ch2 = b.toCharArray();
char temp;
for(int i=0;i<ch1.length;i++){
for(int j=i+1;j<ch1.length;j++){
if(ch1[i]>ch1[j]){
temp = ch1[i];
ch1[i] =ch1[j];
ch1[j] = temp;
}
}
}
for(int i=0;i<ch2.length;i++){
for(int j=i+1;j<ch2.length;j++){
if(ch2[i]>ch2[j]){
temp = ch2[i];
ch2[i] =ch2[j];
ch2[j] = temp;
}
}
}
//System.out.println(ch1);
//System.out.println(ch2);
//int[] charcounta = new int[ch1.length];
for (int i = ch1.length - 1; i >= 0; i--)
{
if(ch1[i]!=ch2[i]){
return false;
}else{
continue;
}
}
return true;
}
return false;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String a = scan.next();
String b = scan.next();
scan.close();
boolean ret = isAnagram(a, b);
System.out.println( (ret) ? "Anagrams" : "Not Anagrams" );
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
seems this is more simpler...