Given two strings s and t, write a function to determine if t is an anagram of s.
For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.
Note:
You may assume the string contains only lowercase alphabets.
<Solution>You may assume the string contains only lowercase alphabets.
想法如下
- 如果長度不同,直接回傳 false
- 因為題目有說,只會包含小寫英文字母,所以可以用長度 26 的 array 來記錄
- 根據 anagram 的定義,在 s 出現的字母,在 t 也一定要出現,且次數也要一樣。因此,當一個字母出現在 s,就將該字母的次數加 1,然後如果該字母也出現在 t,那就把該字母的次數減 1,這樣當歷遍完 s 和 t,如果 t 是 s 的 anagram,則所有的記數應該都要是 0
code 如下
Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public boolean isAnagram(String s, String t) { | |
if(s.length() != t.length()) { | |
return false; | |
} | |
int[] cnt = new int[26]; | |
final int len = s.length(); | |
for(int i = 0; i < len; i++) { | |
cnt[s.charAt(i) - 'a']++; | |
cnt[t.charAt(i) - 'a']--; | |
} | |
for(final int n : cnt) { | |
if(n != 0) { | |
return false; | |
} | |
} | |
return true; | |
} | |
} |
kotlin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
fun isAnagram(s: String, t: String): Boolean { | |
val map = mutableMapOf<Char,Int>() | |
return if (s.length == t.length) { | |
for(i in s.indices) { | |
map[s[i]] = map[s[i]]?.let{it+1} ?: 1 | |
map[t[i]] = map[t[i]]?.let{it-1} ?: -1 | |
} | |
!map.any{it.value > 0} | |
} else { | |
false | |
} | |
} | |
} |
沒有留言:
張貼留言