ITeye博客

Valid Anagram

KickCode · 2016-02-24 05:48 · Leetcode · 编程语言 · Markdown

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.

判断两个词是否为异位构词,我们可以借助计数排序算法的思想来解决,代码如下:


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

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。