Given two strings s and t, write a function to determine if t is an anagram of s.
Example 1:
Input: s = "anagram", t = "nagaram"
Output: true
Approach
Java
import java.util.HashMap;public class ValidAnagram {public static void main(String[] args) {String s = "anagram", t = "nagaram";System.out.println(isAnagram(s, t));}static public boolean isAnagram(String str1, String str2) {// hold char frequencyHashMap<Character, Integer> map = new HashMap<>();// Base case // null checkif (str1.length() == 0 && str2.length() == 0)return true;if (str1 == null || str1.length() == 0 || str2 == null|| str2.length() == 0) {return false;}// calculate frequency of str1for (int i = 0; i < str1.length(); i++) {map.put(str1.charAt(i), map.getOrDefault(str1.charAt(i), 0) + 1);}// check frequency of str1 is equals of str2for (int i = 0; i < str2.length(); i++) {// if element not contain in str1if (!map.containsKey(str2.charAt(i)))return false;// if frequency not equalif (map.get(str2.charAt(i)) == -1)return false;map.put(str2.charAt(i), map.getOrDefault(str2.charAt(i), 0) - 1);}// worst case : check remaining frequencyfor (Character ch : map.keySet()) {if (map.get(ch) > 0) {return false;}}return true;}}
C++
#include <bits/stdc++.h>using namespace std;//function to check if two//strings are anagram or notbool isAnagram(string str1, string str2){int len1 = str1.size();int len2 = str2.size();if (len1 != len2)return false;unordered_map<char, int> ump;for (int i = 0; i < len1; i++){ump[str1[i]]++;}for (int i = 0; i < len2; i++){if (ump[str2[i]] == 0)return false;elseump[str2[i]]--;}for (auto it = ump.begin(); it != ump.end(); it++){if (it->second > 0)return false;}return true;}int main(){string s = "anagram", t = "nagaram";if (isAnagram(s, t))cout << "true";elsecout << "false";return 0;}
No comments:
Post a Comment