简体   繁体   English

Java在字符串中重复的字母检查

[英]Java repeated letter check in string

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.程序需要将重复的字母输出为真,如果没有则输出为假。 Program should not count numbers or symbols as repeated.程序不应计算重复的数字或符号。

For example:例如:

  • User input: Chocolate用户输入:巧克力
    Program Output: True程序输出:真

  • User input: 112 cream用户输入:112奶油
    Program Output: False程序输出:假

Here is another version, based on answer from @rell but with no HashSet or char[] creation.这是另一个版本,基于@rell 的回答,但没有HashSetchar[]

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) .但是对于更长的输入字符串,来自@rell 的版本可能更快,因为他使用带有O(1)查找/插入的HashSet ,并且由于循环为O(n) ,因此总数为O(n) And my solution is O(n^2) (loop O(n) multiplied with indexOf with O(n) ), worst case input would be something like this abcdefghijklmnopqrstuvwxyzz .我的解决方案是O(n^2) (循环O(n)乘以indexOfO(n) ),最坏的情况输入将是这样的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更新修复了流版本中的错误

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;
}

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

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;
    }

1.) Sort the character array. 1.) 对字符数组进行排序。

2.) Iterate through the array to see if ith value == (i+1)th value. 2.) 遍历数组以查看第 i 个值是否 == (i+1) 个值。 If any found, return false.如果找到,则返回 false。 Else, return true.否则,返回真。

Time complexity: O(nlogn) (for sorting)时间复杂度:O(nlogn)(用于排序)

Space complexity: O(1)空间复杂度:O(1)

In order to check that any letter is not repeated more than limited number of times you can use the following method:为了检查任何字母的重复次数是否不超过限制次数,您可以使用以下方法:

public static boolean repeatedMoreThanLimitedLength(String str, int limitLength) {
    Pattern pattern = Pattern.compile("(\\w)\\1+");
    Matcher matcher = pattern.matcher(str);
    while (matcher.find()) {
        if (matcher.group().length() >= limitLength)
            return true;
    }
    return false;
}

Since the stream example from the accepted answer doesn't work in Java 17 (streams can't be reused ), let me provide a sample with a stream supplier that worked for me.由于接受的答案中的流示例在 Java 17 中不起作用(流不能被重用),让我提供一个示例,其中包含对我有用的流供应商

Also, I use chars() method instead of .codePoints() , it's more intuitive as for me.另外,我使用chars() 方法而不是.codePoints() ,这对我来说更直观。

So, let's check, if a string is not an isogram.所以,让我们检查一下,如果一个字符串不是等值线。

import java.util.stream.IntStream;
import java.util.function.Supplier;

public class Isogram {
    private static boolean isNotIsogram(String input) {
        Supplier<IntStream> streamSupplier =
            () -> input.chars().filter(Character::isLetter);
        return streamSupplier.get()
                             .distinct()
                             .count() != streamSupplier.get().count();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM