首页 > 其他 > 详细

Two Strings Are Anagrams

时间:2016-09-09 18:45:39      阅读:248      评论:0      收藏:0      [点我收藏+]

 



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

原文:http://www.cnblogs.com/iwangzheng/p/5857626.html

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