zoukankan      html  css  js  c++  java
  • 判断两个字符串s1 s2所含字符是否相同

    题目摘自CareerCup-Top 150 Questions 4th

    描述如下:

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

    解答如下:

    分析:两个字符串是否相同,解法1就是把这两个字符串一排序,然后看是否==

    解法2是分析两个字符串都含有多少个不同的字符,每个不同的字符含有几个,比如说字符串"abcdefab"含有6个不同字符,分别是a b c d e f,其中各个字符的个数分别是2 2 1 1 1 1 ,那么解法2就可以比较两个字符串这个个数是否相等。代码如下

    说明:

    letters数组里面存放各个字符的个数

    num_unique_chars 里存放字符串有多少个不同的char字符

    num_completed是存放两个字符串s1 s2已经完成比对的字符个数

     1 public static boolean anagram(String s, String t) {
     2     if (s.length() != t.length()) { return false; }
     3     int[] letters = new int[256];
     4     int num_unique_chars = 0;
     5     int num_completed = 0;
     6     char[] s_array = s.toCharArray();
     7     for (char c : s_array) {
     8         if (letters[c] == 0) { ++num_unique_chars; }
     9         ++letters[c];
    10     }
    11     for (int i = 0; i < t.length(); ++i) {
    12         int c = (int) t.charAt(i);
    13         if (letters[c] == 0) { return false; }
    14         --letters[c];
    15         if (letters[c] == 0) {
    16             ++num_completed_t;
    17             if (num_completed_t == num_completed_t) {
    18                 return i == t.length();
    19             }
    20         }
    21     }
    22     return false;
    23 }
  • 相关阅读:
    MVC 易忘备留
    SQL SERVER 常用易忘语句备留
    ThreadStatic特性
    jstack用法
    PV、TPS、QPS是怎么计算出来的?
    性能测试Loadrunner与Mysql
    JVM性能调优监控工具jps、jstack、jmap、jhat、jstat、hprof使用详解
    【MySQL】计算 TPS,QPS 的方式
    【转】jquery 1.3 的 live方法
    【转】HttpCompress
  • 原文地址:https://www.cnblogs.com/ziyoudefeng/p/2706378.html
Copyright © 2011-2022 走看看