心得:
這題要比較兩個字串是否具有相同字母(不管順序),因為這題比較簡單,所以就嘗試用了許多方式解答。
問題:
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.Note:
You may assume the string contains only lowercase alphabets.
答案:
- LinQ –
OrderBy
public class Solution { public bool IsAnagram(string s, string t) { return new string(s.OrderBy(x => x).ToArray()) == new string(t.OrderBy(x => x).ToArray()); } }
- LinQ –
Sort
public class Solution { public bool IsAnagram(string s, string t) { var arr_1 = s.ToList(); var arr_2 = t.ToList(); arr_1.Sort(); arr_2.Sort(); return new string(arr_1.ToArray()) == new string(arr_2.ToArray()); } }
- Normal – Array.Sort
public class Solution { public bool IsAnagram(string s, string t) { var arr_1 = s.ToArray(); var arr_2 = t.ToArray(); Array.Sort(arr_1); Array.Sort(arr_2); return new string(arr_1) == new string(arr_2); } }
- Normal – 硬幹 (會 Time Limit Exceeded)
public class Solution { public bool IsAnagram(string s, string t) { return Sort(s) == Sort(t); } private string Sort(string str){ string result = ""; for(int i = 0; i < 25; i++){ char c = Convert.ToChar(Convert.ToInt16('a') + i); for(int j = 0; j < str.Length; j++){ if(c == str[j]){ result += c; } } } return result; } }
參考: