[虚拟机OA]Fun with Anagrams 玩转同构词

Posted liuliu5151

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[虚拟机OA]Fun with Anagrams 玩转同构词相关的知识,希望对你有一定的参考价值。

Two strings are anagrams if they are permutations of each other. For example, "aaagmnrs" is an anagram of "anagrams". Given an array of strings, remove each string that is an anagram of an earlier string, then return the remaining array in sorted order.


For example, given the strings s = [‘code‘, ‘ecod‘, ‘framer‘, ‘frame], the strings ‘doce‘ and ‘ecod‘ are both anagrams of ‘code‘ so they are removed from the list. The words ‘frame‘ and ‘framer‘ are not anagrams due to the extra in ‘framer‘, so they remain. The final list of strings in alphabetical order is [‘code‘, ‘frame‘, framer].


Function Description

Complete the function funWithArtagrams in the editor below. It must return a list of strings in alphabetical order, ascending.


funWithAnagrams has the following parameters:

s [s[0]...s[n-1]]: an array of strings

Sample Case 0 
Sample Input For Custom Testing 
4
code
aaagmnrs
anagrams
doce

Sample Output 
aaagmnrs
code 

Explanation
aaagmnrs and anagrams are anagrams, code and doce are anagrams. After sorting aaagmnrs comes first.

 

题意:

思路:

代码:

 1  public static List<String> funWithAnagrams(List<String> s)
 2         TreeSet<String> ans = new TreeSet<>();
 3         Map<String, String> map = new HashMap<>();
 4         for(String str : s)
 5             String ana = toAnagram(str);
 6             if(map.containsKey(ana))
 7                 continue;
 8             else
 9                 map.put(ana, str);
10                 ans.add(str);
11             
12         
13         return new ArrayList<>(ans);
14 
15     
16 
17     private  static String toAnagram(String s)
18         int[] ans = new int[26];
19         for(char c : s.toCharArray())
20             ans[c - ‘a‘] ++;
21         
22         StringBuilder sb = new StringBuilder();
23         for (int i = 0; i < 26 ; i++) 
24             while(ans[i] -- > 0)
25                 sb.append((char)(‘a‘ + i));
26             
27         
28         return sb.toString();
29     

 

以上是关于[虚拟机OA]Fun with Anagrams 玩转同构词的主要内容,如果未能解决你的问题,请参考以下文章

[虚拟机OA]Team Formation 2 团队构成

[虚拟机OA]Break a Palindrome 破坏回文串

[虚拟机OA]Build the Subsequences 生成子序列

[虚拟机OA]Group Anagram 变位词归类

[虚拟机OA]Maximal Square 最大正方形

[虚拟机OA]Even Subarray 最多含有K个奇数的子数组