首页 > 其他 > 详细

[leetcode]242.Valid Anagram

时间:2018-10-14 12:46:01      阅读:118      评论:0      收藏:0      [点我收藏+]

题目

Given two strings s and t , 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.

解法

思路

这个题的意思是:字符串s和t是否是由相同的字符构成:比如s中有2个a, 4个b,t中如果一样,就称s和t是anagram。
如果s和t长度不一致,则直接返回false。
因为题目中假设所有字母都是小写,所以我们用一个长度为26的int数组,用每个元素来存s和t中每个字符的个数。s中如果存在,则++;t中如果存在,则--;这样的话,遍历到最后,如果s和t完全相同,那么数组中的每个元素应该都为0。

代码

class Solution {
    public boolean isAnagram(String s, String t) {
        if(s.length() != t.length()) return false;
        int[] count = new int[32];
        for(int i = 0; i < s.length(); i++) {
            count[s.charAt(i) - ‘a‘]++;
            count[t.charAt(i) - ‘a‘]--;
        }
        
        for(int i:count)
            if(i != 0) return false;
        
        return true;
    }
}

[leetcode]242.Valid Anagram

原文:https://www.cnblogs.com/shinjia/p/9785752.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!