LeetCode 242. Valid Anagram #77
quinnwencn
started this conversation in
General
Replies: 1 comment
-
AnalysisThis problem is a little similar to LeetCode 207. We can also map chars to index to solve it. Solution written in Cppclass Solution {
public:
bool isAnagram(string s, string t) {
int slen = s.length();
if (slen != t.length()) {
return false;
}
int letters[26] {0};
for (int i = 0; i < slen; ++i) {
letters[s[i] - 'a']++;
}
for (int i = 0; i < slen; ++i) {
letters[t[i] - 'a']--;
}
for (auto i : letters) {
if (i != 0) {
return false;
}
}
return true;
}
};Solution written in Rustimpl Solution {
pub fn is_anagram(s: String, t: String) -> bool {
if s.len() != t.len() {
return false;
}
let mut visited = vec![0; 26];
let it = s.chars().zip(t.chars());
for (c1, c2) in it {
visited[c1 as usize - 'a' as usize] += 1;
visited[c2 as usize - 'a' as usize] -= 1;
}
for i in visited {
if i != 0 {
return false;
}
}
true
}
} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Description
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
Constraints:
1 <= s.length, t.length <= 5 * 104
s and t consist of lowercase English letters.
Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?
Beta Was this translation helpful? Give feedback.
All reactions