zoukankan      html  css  js  c++  java
  • 4-21刷题

    Two Strings Are Anagrams

    判断两个字符串是否为重组的,没想到太好的方法,直接用计数法简单粗暴。

    public class Solution {
        /**
         * @param s: The first string
         * @param b: The second string
         * @return true or false
         */
        public boolean anagram(String s, String t) {
            // write your code here
            int[] num = new int[270];
            char[] s1 = s.toCharArray();
            char[] t1 = t.toCharArray();
            if (s.length() != t.length()) return false;
            for (int i = 0; i < s.length(); ++i) {
                num[s1[i]]++;
                --num[t1[i]];
            }
            for (int i = 0; i < num.length; ++i) {
                if (num[i] != 0) return false;   
            }
            return true;
        }
    };

     标准答案:

    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 i = 0; i < t.length(); i++) {
                count[(int) t.charAt(i)]--;
                if (count[(int) t.charAt(i)] < 0) {
                    return false;
                }
            }
            return true;
        }
    };

    Compare Strings

    public class Solution {
        /**
         * @param A : A string includes Upper Case letters
         * @param B : A string includes Upper Case letter
         * @return :  if string A contains all of the characters in B return true else return false
         */
        public boolean compareStrings(String A, String B) {
            // write your code here
            int[] num = new int[256];
            for (int i = 0; i < A.length(); ++i) {
                ++num[(int) A.charAt(i)];
            }
            for (int i = 0; i < B.length(); ++i) {
                --num[(int)B.charAt(i)];
                if (num[(int)B.charAt(i)] < 0) return false;
            }
            return true;
        }
    }
  • 相关阅读:
    delphi 滚屏
    delphi Sender和Tag的用法
    delphi res 字符串资源
    delphi queryCommandState
    net图片转格式
    递归数据树结构
    C# winform文件批量转编码 选择文件夹
    SQL可重复执行语句,增删改字段、表、修改默认值
    WEBAPI测试
    调用webservice
  • 原文地址:https://www.cnblogs.com/fripside/p/4444957.html
Copyright © 2011-2022 走看看