zoukankan      html  css  js  c++  java
  • leetcode-242-Valid Anagram

    题目描述:

    Given two strings s and , write a function to determine if t is an anagram of s.

    Example 1:

    Input: s = "anagram", t = "nagaram"
    Output: true
    

    Example 2:

    Input: s = "rat", t = "car"
    Output: false
    

    Note:
    You may assume the string contains only lowercase alphabets.

    Follow up:
    What if the inputs contain unicode characters? How would you adapt your solution to such case?

     

    要完成的函数:

    bool isAnagram(string s, string t) 

     

    说明:

    1、给定两个字符串 s 和 t ,要求判断 s 能不能通过交换位置变成 t ,返回true或者false。

    2、其实就是要我们判断 s 和 t 中的字符出现次数是不是相等,而且两个字符串中只包含小写字母,所以我们定义一个长度为26的vector就可以了。

    代码如下:(附详解)

        bool isAnagram(string s, string t) 
        {
            int s1=s.size(),s2=t.size(),res=0;
            if(s1!=s2)//边界条件
                return false;
            vector<int>count(26,0);//定义一个长度26的vector
            for(int i=0;i<s1;i++)
            {
                count[s[i]-'a']++;//s中的字母要加1
                count[t[i]-'a']--;//t中的字母要减1
            }
            for(int i=0;i<26;i++)
            {
                if(count[i]!=0)//判断最终的26个数值是不是都为0
                    return false;
            }
            return true;
        }
    

    上述代码实测10ms,beats 99.39% of cpp submissions。

     

    3、其他想法(不是那么重要)

    笔者曾经产生过一个想法,用异或来做这道题,如果两个字符串的所有字母都一样,那么必然所有字母的异或结果为0,如果不一样,比如“ab”和“ac”,那么异或结果必然不为0。

    这样子判断起来会快很多。

    但是存在一个问题,如果两个字符串是“aa”和“bb”,异或结果仍然是0,这就很尴尬了。

    所以其实异或结果是0,是两个字符串中的所有字母都一样的,必然条件,而不是充分条件。

    最终还是用统计的方法完成了。

  • 相关阅读:
    Windows Phone自学笔记(2)
    对MVC的初步认识
    CMSIS 的相关知识
    关于机器码的一些疑惑
    关于预编译处理的尝试
    IAR提示错误C:\Program Files\IAR Systems\Embedded Workbench 6.4 Kickstart\arm\bin路径下的armjlink.dll文件
    Spring学习笔记(四)
    Spring学习笔记(三)
    Docker容器数据卷(v创建数据卷)
    Spring5学习笔记(一)
  • 原文地址:https://www.cnblogs.com/chenjx85/p/9117422.html
Copyright © 2011-2022 走看看