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

     1 #include<map>
     2 #include<string>
     3 #include<iterator>
     4 using namespace std;
     5 
     6 class Solution {
     7 public:
     8     bool isAnagram(string s, string t) {
     9         string temp1,temp2,temp3;
    10         int c1,c2;
    11         map<string,int> dictionary1,dictionary2;
    12         for(int i=0;i<s.length();i++) {
    13             temp1=s[i];
    14             ++dictionary1[temp1];}
    15         for(int j=0;j<t.length();j++) {
    16             temp2=t[j];
    17             ++dictionary2[temp2];}
    18             
    19         if(dictionary1.size()!=dictionary2.size()) return false;
    20         for(auto i=dictionary1.begin();i!=dictionary1.end();i++)
    21         {
    22             c1=(*i).second;
    23             temp3=(*i).first;
    24             c2=dictionary2[temp3];
    25             if(c1!=c2) return false;
    26         }
    27         return true;    
    28         
    29     }
    30 };

     看到一个更好的方法:(别人的)

    class Solution {
    public:
        bool isAnagram(string s, string t) {
            vector<int> count(26, 0);  //全部初始化为0
            for(int i = 0; i < s.size(); i ++)
                count[s[i]-'a'] ++;      //把a,b,c转换成下标了- - 不是什么二维,二维应该是vector<vector<int >>
            for(int i = 0; i < t.size(); i ++)
                count[t[i]-'a'] --;
            for(int i = 0; i < 26; i ++)
                if(count[i] != 0)
                    return false;
            return true;
        }
    };

     tips:

     string当然不一定要初始化。

     C++中没有直接判断map是否相等的函数;

     map中有iterator;

     map中的元素是pair,我们可以用first来取关键字,second来取值;

  • 相关阅读:
    VSCode 设置 CPP 代码风格
    KiCad EDA 5.1.2 使用圆形板框时出现无法走线的问题
    oracle的sql优化
    mybatis 自动生成xml文件配置
    sql循环遍历
    XML
    oracle的concat的用法
    oracle 按某个字段查询重复数据
    Xshell 4的上传与下载
    Oracle之锁
  • 原文地址:https://www.cnblogs.com/LUO77/p/4959663.html
Copyright © 2011-2022 走看看