[C#][LeetCode][Easy] 242. Valid Anagram

心得:

這題要比較兩個字串是否具有相同字母(不管順序),因為這題比較簡單,所以就嘗試用了許多方式解答。

問題:

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:

1
2
3
4
5
6


> You may assume the string contains only lowercase alphabets.
答案:

* LinQ - `OrderBy`

public class Solution {
public bool IsAnagram(string s, string t) {

1
2
3
4

By(x => x).ToArray()) == new string(t.OrderBy(x => x).ToArray());
}
}
  • LinQ - Sort
1
2
3
4
5
6
7

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();

oArray()) == new string(arr_2.ToArray());
}
}

1
2
3
4
5




* 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);

1
2
3
4

= new string(arr_2);
}
}
  • Normal - 硬幹 (會 Time Limit Exceeded)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

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;
}
}

參考:

  1. (C#)用迴圈印出字母A到Z%E7%94%A8%E8%BF%B4%E5%9C%88%E5%8D%B0%E5%87%BA%E5%AD%97%E6%AF%8Da%E5%88%B0z)