LeetCode每日一题:有效的字母异位词(No.242)

栏目: 编程工具 · 发布时间: 7年前

给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。
复制代码

示例:

输入: s = "anagram", t = "nagaram"
输出: true

输入: s = "rat", t = "car"
输出: false
复制代码

思考:

这道题先判断s和t的长度,不相等则不可能是字母异或位词。
然后初始化一个int数组记录二十六个字母出现的次数。
遍历s、t,字母在s中出现一次数组对应位置上的数加1,在t中出现一次数组对应位置上的数减去1。
最后数组所有位置元素都为0返回true,即t 是 s 的字母异位词,否则返回false,t 不是 s 的字母异位词。
复制代码

实现:

class Solution {
    public boolean isAnagram(String s, String t) {
        if (s.length() != t.length())
            return false;
        int[] result = new int[26];
        for (int i = 0; i < s.length(); i++) {
            result[s.charAt(i) - 'a']++;
            result[t.charAt(i) - 'a']--;
        }
        for (int count = 0; count < 26; count++)
            if (result[count] != 0)
                return false;
        return true;
    }
}复制代码

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Google's PageRank and Beyond

Google's PageRank and Beyond

Amy N. Langville、Carl D. Meyer / Princeton University Press / 2006-7-23 / USD 57.50

Why doesn't your home page appear on the first page of search results, even when you query your own name? How do other web pages always appear at the top? What creates these powerful rankings? And how......一起来看看 《Google's PageRank and Beyond》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

MD5 加密
MD5 加密

MD5 加密工具

html转js在线工具
html转js在线工具

html转js在线工具