首页 > 代码库 > 242.判断一个字符串是否为另一个的乱序 Valid Anagram

242.判断一个字符串是否为另一个的乱序 Valid Anagram

错误1
"aa"
"bb"
  1. static public bool IsAnagram(string s, string t) {
  2. int sLength = s.Length;
  3. int tLength = t.Length;
  4. if (sLength != tLength) {
  5. return false;
  6. }
  7. char c = ‘ ‘;
  8. int value = 0;
  9. Dictionary<char, int> d = new Dictionary<char, int>();
  10. for (int i = 0; i < sLength; i++) {
  11. c = s[i];
  12. if (d.TryGetValue(c, out value)) {
  13. d[c] += 1;
  14. } else {
  15. d[c] = 1;
  16. }
  17. c = t[i];
  18. if (d.TryGetValue(c, out value)) {
  19. d[c] += 1;
  20. } else {
  21. d[c] = 1;
  22. }
  23. }
  24. foreach(int i in d.Values) {
  25. if (i % 2 != 0) {
  26. return false;
  27. }
  28. }
  29. return true;
  30. }


解法
  1. public class Solution {
  2. public bool IsAnagram(string s, string t) {
  3. int sLength = s.Length;
  4. int tLength = t.Length;
  5. if (sLength != tLength) {
  6. return false;
  7. }
  8. char[] sChars = s.ToCharArray();
  9. char[] tChars = t.ToCharArray();
  10. Array.Sort(sChars);
  11. Array.Sort(tChars);
  12. for (int i = 0; i < sLength; i++) {
  13. if (sChars[i] != tChars[i]) {
  14. return false;
  15. }
  16. }
  17. return true;
  18. }
  19. }



来自为知笔记(Wiz)


242.判断一个字符串是否为另一个的乱序 Valid Anagram