Find the first un-repeated character in a string

后端 未结 30 1439
猫巷女王i
猫巷女王i 2020-11-27 18:29

What is the quickest way to find the first character which only appears once in a string?

30条回答
  •  天命终不由人
    2020-11-27 19:15

    The following solution is an elegant way to find the first unique character within a string using the new features which have been introduced as part as Java 8. This solution uses the approach of first creating a map to count the number of occurrences of each character. It then uses this map to find the first character which occurs only once. This runs in O(N) time.

    import static java.util.stream.Collectors.counting;
    import static java.util.stream.Collectors.groupingBy;
    
    import java.util.Arrays;
    import java.util.List;
    import java.util.Map;
    
    // Runs in O(N) time and uses lambdas and the stream API from Java 8
    //   Also, it is only three lines of code!
    private static String findFirstUniqueCharacterPerformantWithLambda(String inputString) {
      // convert the input string into a list of characters
      final List inputCharacters = Arrays.asList(inputString.split(""));
    
      // first, construct a map to count the number of occurrences of each character
      final Map characterCounts = inputCharacters
        .stream()
        .collect(groupingBy(s -> s, counting()));
    
      // then, find the first unique character by consulting the count map
      return inputCharacters
        .stream()
        .filter(s -> characterCounts.get(s) == 1)
        .findFirst()
        .orElse(null);
    }
    

提交回复
热议问题