判断两个字符串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 }

 

转载于:https://www.cnblogs.com/ziyoudefeng/archive/2012/09/27/2706378.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值