有三种方法可以找到第一个非重复字符。每个都使用自己的算法来完成这个编程任务。
第一种算法在getFirstNonRepeatedChar(String str)方法中实现。它首先从给定的String获取字符数组并循环遍历它,以构建一个哈希表,其中字符为键,其计数为值。在下一步中,它遍历LinkedHashMap以查找值为1的条目,这是您的第一个非重复字符,因为LinkedHashMap维护插入顺序,并且我们从头到尾迭代字符数组。不好的部分是它需要两次迭代,第一次与String中的字符数成比例,第二次与String中的重复字符数成比例。在最坏的情况下,String最后包含非重复字符,解决此问题需要2 * N时间。
第二种方法是在firstNonRepeatingChar(String word)上编码,该解决方案只在一次传递中找到String中的第一个非重复字符。它应用了经典的时空权衡技术。使用两个存储来减少一次迭代,标准空间与时间的权衡。由于我们分别存储重复和非重复的字符,因此在迭代结束时,List中的第一个元素是String中的第一个非重复字符。这个稍微好于前一个,但如果String中没有非重复字符,则选择返回null或空字符串。
第三种方法是在firstNonRepeatedCharacter(String word)方法中实现的。它与第一个非常相似,只是除了LinkedHashMap之外,我们使用了HashMap。由于以后不保证任何顺序,我们必须依靠原始字符串来查找第一个非重复字符。这是第三种解决方案的算法。第一步:扫描字符串并在HashMap中存储每个字符的计数。第二步:遍历String并从Map获取每个字符的计数。由于我们要从第一个字符到最后一个字符遍历字符串,当任何字符的计数为1时,我们将中断,这是第一个非重复字符。这里的顺序是通过再次遍历字符串来实现的。
<b>import</b> java.io.IOException; <b>import</b> java.util.ArrayList; <b>import</b> java.util.HashMap; <b>import</b> java.util.HashSet; <b>import</b> java.util.LinkedHashMap; <b>import</b> java.util.List; <b>import</b> java.util.Map; <b>import</b> java.util.Map.Entry; <b>import</b> java.util.Set; <font><i>/** * Java Program to find first duplicate, non-repeated character in a String. * It demonstrate three simple example to do this programming problem. * * @author Javarevisited */</i></font><font> <b>public</b> <b>class</b> Programming { </font><font><i>/* * Using LinkedHashMap to find first non repeated character of String * Algorithm : * Step 1: get character array and loop through it to build a * hash table with char and their count. * Step 2: loop through LinkedHashMap to find an entry with * value 1, that's your first non-repeated character, * as LinkedHashMap maintains insertion order. */</i></font><font> <b>public</b> <b>static</b> <b>char</b> getFirstNonRepeatedChar(String str) { Map<Character,Integer> counts = <b>new</b> LinkedHashMap<>(str.length()); <b>for</b> (<b>char</b> c : str.toCharArray()) { counts.put(c, counts.containsKey(c) ? counts.get(c) + 1 : 1); } <b>for</b> (Entry<Character,Integer> entry : counts.entrySet()) { <b>if</b> (entry.getValue() == 1) { <b>return</b> entry.getKey(); } } <b>throw</b> <b>new</b> RuntimeException(</font><font>"didn't find any non repeated Character"</font><font>); } </font><font><i>/* * Finds first non repeated character in a String in just one pass. * It uses two storage to cut down one iteration, standard space vs time * trade-off.Since we store repeated and non-repeated character separately, * at the end of iteration, first element from List is our first non * repeated character from String. */</i></font><font> <b>public</b> <b>static</b> <b>char</b> firstNonRepeatingChar(String word) { Set<Character> repeating = <b>new</b> HashSet<>(); List<Character> nonRepeating = <b>new</b> ArrayList<>(); <b>for</b> (<b>int</b> i = 0; i < word.length(); i++) { <b>char</b> letter = word.<b>char</b>At(i); <b>if</b> (repeating.contains(letter)) { <b>continue</b>; } <b>if</b> (nonRepeating.contains(letter)) { nonRepeating.remove((Character) letter); repeating.add(letter); } <b>else</b> { nonRepeating.add(letter); } } <b>return</b> nonRepeating.get(0); } </font><font><i>/* * Using HashMap to find first non-repeated character from String in Java. * Algorithm : * Step 1 : Scan String and store count of each character in HashMap * Step 2 : traverse String and get count for each character from Map. * Since we are going through String from first to last character, * when count for any character is 1, we break, it's the first * non repeated character. Here order is achieved by going * through String again. */</i></font><font> <b>public</b> <b>static</b> <b>char</b> firstNonRepeatedCharacter(String word) { HashMap<Character,Integer> scoreboard = <b>new</b> HashMap<>(); </font><font><i>// build table [char -> count]</i></font><font> <b>for</b> (<b>int</b> i = 0; i < word.length(); i++) { <b>char</b> c = word.<b>char</b>At(i); <b>if</b> (scoreboard.containsKey(c)) { scoreboard.put(c, scoreboard.get(c) + 1); } <b>else</b> { scoreboard.put(c, 1); } } </font><font><i>// since HashMap doesn't maintain order, going through string again</i></font><font> <b>for</b> (<b>int</b> i = 0; i < word.length(); i++) { <b>char</b> c = word.<b>char</b>At(i); <b>if</b> (scoreboard.get(c) == 1) { <b>return</b> c; } } <b>throw</b> <b>new</b> RuntimeException(</font><font>"Undefined behaviour"</font><font>); } } </font>
查找第一个唯一字符的JUnit测试
下面是一些JUnit测试案例来测试每个方法。我们测试不同类型的输入,一个包含重复项,另一个不包含重复项。由于程序没有定义空字符串、空字符串的情况下要做什么,以及如果只包含重复项,则返回什么,所以您可以选用有意义的方式来做。
<b>import</b> <b>static</b> org.junit.Assert.*; <b>import</b> org.junit.Test; <b>public</b> <b>class</b> ProgrammingTest { @Test <b>public</b> <b>void</b> testFirstNonRepeatedCharacter() { assertEquals('b', Programming.firstNonRepeatedCharacter(<font>"abcdefghija"</font><font>)); assertEquals('h', Programming.firstNonRepeatedCharacter(</font><font>"hello"</font><font>)); assertEquals('J', Programming.firstNonRepeatedCharacter(</font><font>"Java"</font><font>)); assertEquals('i', Programming.firstNonRepeatedCharacter(</font><font>"simplest"</font><font>)); } @Test <b>public</b> <b>void</b> testFirstNonRepeatingChar() { assertEquals('b', Programming.firstNonRepeatingChar(</font><font>"abcdefghija"</font><font>)); assertEquals('h', Programming.firstNonRepeatingChar(</font><font>"hello"</font><font>)); assertEquals('J', Programming.firstNonRepeatingChar(</font><font>"Java"</font><font>)); assertEquals('i', Programming.firstNonRepeatingChar(</font><font>"simplest"</font><font>)); } @Test <b>public</b> <b>void</b> testGetFirstNonRepeatedChar() { assertEquals('b', Programming.getFirstNonRepeatedChar(</font><font>"abcdefghija"</font><font>)); assertEquals('h', Programming.getFirstNonRepeatedChar(</font><font>"hello"</font><font>)); assertEquals('J', Programming.getFirstNonRepeatedChar(</font><font>"Java"</font><font>)); assertEquals('i', Programming.getFirstNonRepeatedChar(</font><font>"simplest"</font><font>)); } } </font>
这就是如何在Java中找到String的第一个非重复字符。我们已经看到了解决这个问题的三种方法,虽然它们使用了非常相似的逻辑,但它们彼此不同。这个程序也非常适合初学者掌握Java Collection框架。它使您有机会探索不同的Map实现,并了解HashMap和LinkedHashMap之间的区别,以决定何时使用它们。