Two Strings Are Anagrams

Posted 冰凌花花~

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Two Strings Are Anagrams相关的知识,希望对你有一定的参考价值。

 



Write a method anagram(s,t) to decide if two strings are anagrams or not.

 判断两个字符串里的字符是否相同,也就是是否能够通过改变字母顺序而变成相同的字符串。

如果是返回true,如果不是返回false。

 

Clarification

What is Anagram?
- Two strings are anagram if they can be the same after change the order of characters.

Example

Given s = "abcd", t = "dcab", return true.
Given s = "ab", t = "ab", return true.
Given s = "ab", t = "ac", return false.

 

 

public class Solution {
    /**
     * @param s: The first string
     * @param b: The second string
     * @return true or false
     */
    public boolean anagram(String s, String t) {
        if (s.length() != t.length()) {
            return false;
        }
        int[] count = new int[256];
        
        for(int i = 0; i < s.length(); i++) {
            count[(int) s.charAt(i)]++;
        }
        
        for(int j = 0; j < t.length(); j++) {
            count[(int) t.charAt(j)]--;
            if (count[(int) t.charAt(j)] < 0){
                return false;
            }
        }
        return true;
    }
};

 

以上是关于Two Strings Are Anagrams的主要内容,如果未能解决你的问题,请参考以下文章

Two Strings Are Anagrams

未完成 Given an array of strings, return all groups of strings that are anagrams.

[LeetCode] 2068. Check Whether Two Strings are Almost Equivalent

Two Anagrams 记录这个棒的操作

Two Anagrams 记录这个棒的操作

There Are Two Types Of Burgers (Educational Codeforces Round 71)