zoukankan      html  css  js  c++  java
  • 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.

    Analyse: This question actually asks us to judge whether two strings have the same alphabats, i.e. they have same alphabats set and each alphabat has the occurence. 

    1. judge equality after sorting.

        Runtime: 76ms.

    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         return s == t;
    7     }
    8 };

    2. Count the occurence of each alphabat and compare the occurence.

        Runtime: 12ms.

     1 class Solution {
     2 public:
     3     bool isAnagram(string s, string t) {
     4         if(s.length() != t.length()) return false;
     5         
     6         int arrS[26] = {0}, arrT[26] = {0};
     7         for(int i = 0; i < s.length(); i++){
     8             arrS[s[i] - 'a']++;
     9             arrT[t[i] - 'a']++;
    10         }
    11         for(int j = 0; j < 26; j++){
    12             if(arrS[j] != arrT[j]) return false;
    13         }
    14         return true;
    15     }
    16 };
  • 相关阅读:
    MySQL视图
    MySQL触发器
    SQL语法详解
    MySQL函数和操作符
    MySQL常用查询
    MySQL数据类型
    MySQL操作详解
    MySQL学习-SQL约束
    MySQL 其它基本操作
    MySQL创建数据库并插入数据
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4696850.html
Copyright © 2011-2022 走看看