字符串——变位词判断

来源:互联网 发布:linux系统管理员薪水 编辑:程序博客网 时间:2024/06/15 15:34
/** * 题目描述: *  写出一个函数 anagram(s, t),判断两个字符串是否为变位词(通过改变字母顺序变为一样的字符串)。 *  变位词:两个字符串通过改变字母顺序可以变为一样的字符串 *  * 样例 *  给出 s = "abcd", t="dcab", 返回 true *  给出 s = "ab", t = "ab", 返回 true. *  给出 s = "ab", t = "ac", 返回 false. *  * 分析 *  这种题目只需判断是否具有相同的字符,以及字符的数量是否相等 *  技巧是新建一个数组用于记录,若有就加一,多个就继续加一 *  再在另一个字符串里减一,最后如果碰到小于0的,就说明字符数不相等或者没有 *  */public class Anagram {    public static void main(String[] args) {        String s1 = "abaaa";        String s2 = "aaaab";        Boolean result = Anagram.anagram(s1, s2);        System.out.println(s1 + " 与 " + s2 + " 是变位词:" + result);    }    /**     * @param s: The first string     * @param b: The second string     * @return true or false     */    public static Boolean anagram(String s, String t) {        //两个字符串长度不相等        if(s.length() != t.length()) return false;        int[] count = new int[256];        //统计字符串s中每个字符的数目        for (int i = 0; i < s.length(); i++) {            count[(int) s.charAt(i)]++;        }        for (int i = 0; i < t.length(); i++) {            //将字符串t与字符串s中字符数目比较,比较结果相等则减一,比较结果小于0则返回错误            count[(int) t.charAt(i)]--;            if(count[(int) t.charAt(i)] < 0) return false;        }        return true;    }}
0 0
原创粉丝点击