Java repeated letter check in string

后端 未结 5 517
余生分开走
余生分开走 2021-01-27 12:43

I\'m having problem figuring out how to check from users input letters that were repeated. Program needs to output repeated letter as true and if there isn\'t any then as false.

相关标签:
5条回答
  • 2021-01-27 13:11

    Here is another version, based on answer from @rell but with no HashSet or char[] creation.

    private static boolean check(String input) {
        for (int i = 0; i < input.length(); i++) {
            char ch = input.charAt(i);
            if (Character.isLetter(ch) && input.indexOf(ch, i + 1) != -1) {
                return true;
            }
        }
        return false;
    }
    

    For smaller input strings, this will most likely be faster because of that. But for longer input strings, the version from @rell is potentially faster as he is using a HashSet with O(1) lookup/insert, and since the loop is O(n) the total is O(n). And my solution is O(n^2) (loop O(n) multiplied with indexOfwith O(n)), worst case input would be something like this abcdefghijklmnopqrstuvwxyzz.

    Update Another version with streams.

    private static boolean check(String input) {
        IntStream characters = input.codePoints().filter(Character::isLetter);
        return characters
                .distinct()
                .count() == characters.count();
    }
    

    Update Fixed bug in stream version

    0 讨论(0)
  • 2021-01-27 13:16

    1.) Sort the character array.

    2.) Iterate through the array to see if ith value == (i+1)th value. If any found, return false. Else, return true.

    Time complexity: O(nlogn) (for sorting)

    Space complexity: O(1)

    0 讨论(0)
  • 2021-01-27 13:18

    Try this :

        String username ;
        char[] x = username.toCharArray();
        boolean duplicates=false;
        for (j=0;j<x.length;j++)
          for (k=j+1;k<x.length;k++)
            if (x[k] == x[j])
              duplicates=true
    
    0 讨论(0)
  • 2021-01-27 13:30
    private static boolean check(String input) {
        Set<Character> tmp = new HashSet<Character>();
        for(char ch : input.toCharArray()) {
            if (Character.isLetter(ch) && !tmp.add(ch)) {
                return true;
            }
        }
        return false;
    }
    
    0 讨论(0)
  • 2021-01-27 13:34

    We can reduce to Single loop with this.

        boolean checkDuplicates(char[] x)
        {
         Set<char> xSet = new HashSet<char>();
           for (char c : x)
           {
            if (xSet.contains(c)) return true;
            xSet.add(i);
           }
         return false;
        }
    
    0 讨论(0)
提交回复
热议问题