-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidAnaCopy.java
More file actions
52 lines (44 loc) · 1.55 KB
/
validAnaCopy.java
File metadata and controls
52 lines (44 loc) · 1.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import java.util.HashMap;
public class validAnaCopy {
public static boolean isAnagram(String s, String t) {
if (s.length() != t.length()) return false;
HashMap<Character, Integer> sfreq = new HashMap<>();
for (Character letter : s.toCharArray()) {
sfreq.put(letter, sfreq.getOrDefault(letter, 0)+1);
}
for (Character letter : t.toCharArray()) {
if (!sfreq.containsKey(letter)) return false;
int count = sfreq.get(letter);
if (count <= 0) return false;
sfreq.put(letter, count -1);
}
return true;
}
public static void main(String[] args) {
// String s1 = "anagram";
// String t1 = "nagaram";
// System.out.println("Output1: " + isAnagram(s1, t1));
String s2 = "rat";
String t2 = "car";
System.out.println("Output1: " + isAnagram(s2, t2));
}
}
/*
Time: O(n); n is length of strings s and t
Space:
if not equal length, return false
create hash of letter, frequency, for string s
if shash does not have letter in t return false
if count <= 0 return false
for string t, remove elements from hash
return if hash is empty
* https://leetcode.com/problems/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 all the original letters exactly once.
Example 1:
Input: s = "anagram", t = "nagaram"
Output: true
Example 2:
Input: s = "rat", t = "car"
Output: false
*/