Anagram, 애니어그램
단어나 문장의 나열의 순서를 변경했을 때 다른 의미를 가지는 단어나 문장
https://www.hackerrank.com/challenges/java-anagrams/problem?isFullScreen=true
import java.util.Scanner;
public class Solution {
static boolean isAnagram(String a, String b) {
// Complete the function
boolean result = false;
String stringA = a.toLowerCase();
String stringB = b.toLowerCase();
String replaceA = stringA;
String replaceB = stringB;
if(stringA.length() == stringB.length()){
for(int i=0; i<stringA.length(); i++){
String deleteText = stringA.substring(i,i+1);
replaceA = replaceA.replaceFirst(deleteText, "");
replaceB = replaceB.replaceFirst(deleteText, "");
}
if(replaceA.equals(replaceB) ){
result = true;
}
}
return result;
}
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" );
}
}
=> 우선 대소문자를 구분하지 않기 위해서 소문자로 변경했다.
그리고 어떻게 문자별 숫자를 셀 수 있을까하다가
한글자씩 지우면 되지 않을까 하는 생각이 들었다.
...
String stringA = a.toLowerCase();
String stringB = b.toLowerCase();
char[] arr1 = stringA.toCharArray();
char[] arr2 = stringB.toCharArray();
java.util.Arrays.sort(arr1);
java.util.Arrays.sort(arr2);
return java.util.Arrays.equals(arr1, arr2);
toCharArray()
문자열을 char배열 형태로 변경한다.(공백포함)
Arrays.sort()
배열을 오름차순으로 정렬
Arrays.equals()
배열 내용 비교
CAT are CAT, ACT, tac, TCA, aTC, and CtA.
Function Description
Complete the isAnagram function in the editor.
isAnagram has the following parameters:
- string a: the first string
- string b: the second string
Returns
- boolean: If and are case-insensitive anagrams, return true. Otherwise, return false.
Input Format
Constraints
- Strings and consist of English alphabetic characters.
- The comparison should NOT be case sensitive.
Sample Input 0
anagram
margana
Sample Output 0
Anagrams
Explanation 0
A or a | 3 | 3 |
G or g | 1 | 1 |
N or n | 1 | 1 |
M or m | 1 | 1 |
R or r | 1 | 1 |
The two strings contain all the same letters in the same frequencies, so we print "Anagrams".
Sample Input 1
anagramm
marganaa
Sample Output 1
Not Anagrams
Explanation 1
A or a | 3 | 4 |
G or g | 1 | 1 |
N or n | 1 | 1 |
M or m | 2 | 1 |
R or r | 1 | 1 |
The two strings don't contain the same number of a's and m's, so we print "Not Anagrams".
Sample Input 2
Hello
hello
Sample Output 2
Anagrams
Explanation 2
E or e | 1 | 1 |
H or h | 1 | 1 |
L or l | 2 | 2 |
O or o | 1 | 1 |
The two strings contain all the same letters in the same frequencies, so we print "Anagrams".
'HackerRank > JAVA' 카테고리의 다른 글
[못품]Java Regex (0) | 2024.01.17 |
---|---|
java String Tokens (0) | 2024.01.17 |
Java String Reverse (0) | 2024.01.17 |
Java Substring Comparisons (0) | 2024.01.17 |
Java Substring (0) | 2024.01.16 |