码迷,mamicode.com
首页 > 其他好文 > 详细

未完成 Given an array of strings, return all groups of strings that are anagrams.

时间:2017-06-23 19:29:46      阅读:234      评论:0      收藏:0      [点我收藏+]

标签:span   public   logs   als   i++   second   util   java   ati   

 1 import java.util.ArrayList;
 2 import java.util.HashSet;
 3 import java.util.List;
 4 import java.util.Set;
 5 
 6 /**
 7  * Created by cuihongyu on 2017/06/23.
 8  */
 9 public class Solution {
10 
11     public static void main(String[] args) {
12         String[] strings = {"", "", "eat", "den", "tea", "and", "ate"};
13         System.out.print(anagrams(strings));
14     }
15 
16     /**
17      * @param strs A list of strings
18      * @return A list of strings
19      */
20     public static List<String> anagrams(String[] strs) {
21         List<String> result = new ArrayList<String>();
22         if (strs == null) {
23             return result;
24         }
25         for (int index1 = 0; index1 < strs.length; index1++) {
26             boolean hasAnagram = false;
27             int index2;
28             for (index2 = index1 + 1; index2 < strs.length; index2++) {
29                 if (isAnagram(strs[index1], strs[index2])) {
30                     if (!hasAnagram) {
31                         result.add(strs[index1]);
32                     }
33                     result.add(strs[index2]);
34                     hasAnagram = true;
35                 }
36             }
37         }
38 //        Set<String> set = new HashSet<String>();
39 //        set.addAll(result);
40 //        result.clear();
41 //        result.addAll(set);
42         return result;
43     }
44     
45     private static boolean isBreak(int index, boolean s2) {
46         
47         return s2;
48     }
49     
50     /**
51      * 判断两个数是否是anagram
52      * @param s1 The first string
53      * @param s2 The second string
54      * @return true or false
55      */
56     private static boolean isAnagram(String s1, String s2) {
57         if (s1.length() != s2.length()) {
58             return false;
59         }
60         char[] charS1 = s1.toCharArray();
61         char[] charS2 = s2.toCharArray();
62         int[] nums = new int[127];
63         int index;
64         for (int i = 0; i < s1.length(); i++) {
65             index = charS1[i] - ‘a‘;
66             nums[index]++;
67             index = charS2[i] - ‘a‘;
68             nums[index]--;
69         }
70         for (int j = 0; j < 127; j++) {
71             if (nums[j] != 0) {
72                 return false;
73             }
74         }
75         return true;
76     }
77 }

 

未完成 Given an array of strings, return all groups of strings that are anagrams.

标签:span   public   logs   als   i++   second   util   java   ati   

原文地址:http://www.cnblogs.com/CuiHongYu/p/7071141.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!