zoukankan      html  css  js  c++  java
  • LeetCode 242 Valid Anagram

    Problem:

    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.

    Summary:

    给出字符串s和t,判断t是不是s的相同字母异序词。

    Analysis:

    1. Hash表,记录s中字母出现的次数,再判断t中的字母是否有相同出现频率。此方法也可以由map实现。

     1 class Solution {
     2 public:
     3     bool isAnagram(string s, string t) {
     4         int len1 = s.size(), len2 = t.size(), ch[26] = {0};
     5         
     6         for (int i = 0; i < len1; i++) {
     7             int tmp = s[i] - 'a';
     8             ch[tmp]++;
     9         }
    10         
    11         for (int i = 0; i < len2; i++) {
    12             int tmp = t[i] - 'a';
    13             ch[tmp]--;
    14         }
    15         
    16         for (int i = 0; i < 26; i++) {
    17             if (ch[i]) {
    18                 return false;
    19             }
    20         }
    21         
    22         return true;
    23     }
    24 };

    2. 分别给两字符串中字符由小到大排序,判断排序后两字符串是否相等即可。但这个方法效率较低。

    1 class Solution {
    2 public:
    3     bool isAnagram(string s, string t) {
    4         sort(s.begin(), s.end());
    5         sort(t.begin(), t.end());
    6         
    7         return s == t ? true : false;
    8     }
    9 };
  • 相关阅读:
    PHP多台服务器跨域SESSION共享
    php发送post请求到nodejs服务器
    xampp使用phpunit
    MarkdownPad 2
    php安装memcache注意事项
    yii 基础版用rbac-plus
    yii2高级版账号密码问题
    yii2 rbac-plus的使用
    manjaro-VM虚拟机vmmon错误
    Java并发包中的线程池ThreadPoolExecutor
  • 原文地址:https://www.cnblogs.com/VickyWang/p/6009864.html
Copyright © 2011-2022 走看看