zoukankan      html  css  js  c++  java
  • Cracking the Coding Interview Q1.3

    Write a method to decide if two strings are anagrams or not.

    package chapter1;
    
    /**
     * Write a method to decide if two strings are anagrams or not.
     * 
     * @author jd
     * 
     */
    public class Q1_3 {
        /**
         * Assume the char set is extended ASCII, we check whether the two string
         * have identical counts for each char.
         */
        static boolean permutation(String a, String b) {
            if (a == null)
                return b == null;
            int[] count = new int[256];
            for (int i = 0; i < a.length(); i++) {
                count[a.charAt(i)]++;
            }
    
            //this part is so nice
            for (int i = 0; i < b.length(); i++) {
                count[b.charAt(i)]--;
                if (count[b.charAt(i)] < 0)
                    return false;
            }
    
            return true;
        }
    
        public static void main(String[] args) {
            String[][] pairs = { { "apple", "papel" }, { "carrot", "tarroc" }, { "hello", "llloh" } };
            for (String[] pair : pairs) {
                String word1 = pair[0];
                String word2 = pair[1];
                boolean anagram = permutation(word1, word2);
                System.out.println(word1 + ", " + word2 + ": " + anagram);
            }
        }
    
    }
    View Code

    Solution:

    public static boolean permutation(String s, String t) {
            if (s.length() != t.length()) {
                return false;
            }
            
            int[] letters = new int[256];
             
            char[] s_array = s.toCharArray();
            for (char c : s_array) { // count number of each char in s.
                letters[c]++;  
            }
              
            for (int i = 0; i < t.length(); i++) {
                int c = (int) t.charAt(i);
                if (--letters[c] < 0) {
                    return false;
                }
            }
              
            return true;
        }
    View Code
  • 相关阅读:
    git常用操作命令
    如何编写高质量代码
    Chrome调试工具简单介绍
    使用eclipse+tomcat搭建本地环境
    chrome设置--disable-web-security解决跨域
    利用Maven管理工程项目本地启动报错及解决方案
    用户输入验证【提升篇】
    简单【用户输入验证】
    【消息框】的返回值
    【消息框】的4种显示形式
  • 原文地址:https://www.cnblogs.com/jdflyfly/p/3821667.html
Copyright © 2011-2022 走看看