-
leetcode top interview 150 | Valid Anagram | HashMapPS 2023. 9. 1. 09:43
Question
문자열 t가 문자열 s의 애너그램이면 true, 아니면 false를 리턴한다.
Accepted Code - HashMap
import java.util.*; class Solution { public boolean isAnagram(String s, String t) { if(s.length() != t.length()) return false; Map<Character, Integer> map = new HashMap<>(); for(char c : s.toCharArray()){ map.put(c, map.getOrDefault(c, 0) + 1); } for(char c : t.toCharArray()){ if(map.containsKey(c) && map.get(c) > 0) map.put(c, map.get(c) - 1); else return false; } return true; } }
Solve
https://yooyouny.tistory.com/20
이전에 풀었던 문제와 동일한 문제, 다만 해당 문제는 문자의 개수까지 같아야한다.
따라서 아예 s와 t의 길이가 다르면 false로 리턴해주고, HashMap을 활용하여 s의 문자가 t에 contains되어있는지, cnt 차감이 가능한지 등을 확인해줬다.
Valid Anagram - LeetCode
Can you solve this real interview question? Valid Anagram - Given two strings s and t, return true if t is an anagram of s, and false otherwise. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using
leetcode.com
'PS' 카테고리의 다른 글
leetcode top interview 150 | Find Peak Element | Binary Search (0) 2023.09.05 leetcode top interview 150 | Min Stack | ArrayList (0) 2023.09.01 leetcode top interview 150 | Ransom Note | HashMap (0) 2023.09.01 leetcode top interview 150 | Contains Duplicate II | HashMap (0) 2023.09.01 leetcode top interview 150 | Evaluate Reverse Polish Notation | Stack (0) 2023.08.31