158 两个字符串是变位词

原题网址: http://www.lintcode.com/zh-cn/problem/two-strings-are-anagrams/#

写出一个函数 anagram(s, t) 判断两个字符串是否可以通过改变字母的顺序变成一样的字符串。

说明

What is Anagram?
- Two strings are anagram if they can be the same after change the order of characters.

样例

给出 s = "abcd",t="dcab",返回 true.
给出 s = "ab", t = "ab", 返回 true.
给出 s = "ab", t = "ac", 返回 false.

挑战 

O(n) time, O(1) extra space

 
方法一:对s与t排序,然后比较
 1 class Solution {
 2 public:
 3     /**
 4      * @param s: The first string
 5      * @param t: The second string
 6      * @return: true or false
 7      */
 8     bool anagram(string &s, string &t) {
 9         // write your code here
10         if (s.empty()&&t.empty())
11     {
12         return true;
13     }
14     if (s.empty()&&(t.empty()==false))
15     {
16         return false;
17     }
18     if (t.empty()&&(s.empty()==false))
19     {
20         return false;
21     }
22     int sizes=s.size();
23     int sizet=t.size();
24     if (sizes!=sizet)
25     {
26         return false;
27     }
28     sort(s.begin(),s.end());
29     sort(t.begin(),t.end());
30     if (s==t)
31     {
32         return true;
33     }
34     else
35     {
36         return false;
37     }
38     }
39 };

 

方法二:参考:https://blog.csdn.net/hpingwu/article/details/49765155   

ASCⅡ128个字符

 1 class Solution {
 2 public:
 3     /**
 4      * @param s: The first string
 5      * @param t: The second string
 6      * @return: true or false
 7      */
 8     bool anagram(string &s, string &t) {
 9         // write your code here
10         if (s.empty()&&t.empty())
11         {
12             return true;
13         }
14         if (s.empty()&&(t.empty()==false))
15         {
16             return false;
17         }
18         if (t.empty()&&(s.empty()==false))
19         {
20             return false;
21         }
22         int sizes=s.size();
23         short ch[128];
24         memset(ch,0,sizeof(ch));
25         for (int i=0;i<sizes;i++)
26         {
27             ch[s[i]]++;
28             ch[t[i]]--;
29         }
30         for (int i=0;i<128;i++)
31         {
32             if (ch[i]!=0)
33             {
34                 return false;
35             }
36         }
37         return true;
38     }
39 };

更多参考:

https://www.cnblogs.com/libaoquan/p/7262637.html

posted @ 2018-03-26 19:42  eeeeeeee鹅  阅读(284)  评论(0编辑  收藏  举报