【ACM从零开始】LeetCode OJ-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:
You may assume the string contains only lowercase alphabets.

题目大意:比较两个字符串是否有相同的字母个数组成。

解题思路:这里想到两种方法。

思路一:

建立一个表,记录字符串s里每个字符的个数,再与字符串t比对。

思路二:

将两个字符串的元素排序,然后比较大小。

首先是思路二的代码,提示TLE,可能是用冒泡排序导致时间复杂度过高,有空再修改。

- -在VS上跑是正常的,LeetCode上测试的字符串太长导致TLE,看来这个思路不可取,贴上能正常运行的代码。

class Solution {
public:
    bool isAnagram(string s, string t) {
      int m, n;
      m = s.length();
         n = t.length();
         s = BubbleSort(s, s.length() + 1);
            t = BubbleSort(t, t.length() + 1);
         return s == t;
    }
    string BubbleSort(string p, int n)
    {
      for (int i = 0; i < n; i++)
      {
           for (int j = 0; j < n - i - 1; j++)
           {
               if (p[j] > p[j + 1])
            {
                char tmp = p[j];
                     p[j] = p[j + 1];
                               p[j + 1] = tmp;
               }
            }
         }
         return p;
     }
};

思路一,AC代码:

class Solution {

public:    

  bool isAnagram(string s, string t) {        

    int count[26] = {0};     

    int m, n;     

    m = s.length();     

    n = t.length();

       for (int i = 0; i < m;i++)           

      count[s[i] - 'a']++;      

     for (int j = 0; j < n;j++)          

      count[t[j] - 'a']--;           

     for (int k = 0; k < sizeof(count) / sizeof(count[0]);k++)      

       if (count[k] != 0)       

         return false;            

       return true;    

  }

};

posted @ 2015-10-07 22:03  Shvier  阅读(218)  评论(0编辑  收藏  举报