码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-01-10 23:40:51      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:笔记   cti   错误   sort   char   static   code   val   isa   

错误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. }





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

标签:笔记   cti   错误   sort   char   static   code   val   isa   

原文地址:http://www.cnblogs.com/xiejunzhao/p/ae8fa540b23f82529fb97b80eec579f8.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!