1

我正在尝试通过在 Java 中使用 set 来确定字符串是否为 pangram

我已经尝试了下面的代码。现在输出显示为不是 pangram,但它应该是 pangram。请告诉我我的解决方案有什么问题

    // Java Program to illustrate Pangram 
    import java.util.*;
    public class GFG 
    { 
        public static boolean checkPangram (String str) 
        { 
            int index = 0,count=0; 
            char s[]=str.toCharArray();
            Set<Character> hs= new HashSet<Character>();
            for(index=0;index<str.length();index++)
            {
                hs.add(s[index]); 
            }
            Iterator<Character> i=hs.iterator();
            while(i.hasNext())
            {
              count++;
              i.next();
            }
            if(count==26)
              return true;
            return false;
        } 

        // Driver Code 
        public static void main(String[] args) 
        { 
            String str = "the quick brown fox jumps over the lazy dog"; 

            if (checkPangram(str) == true) 
                System.out.print(str + " is a pangram."); 
            else
                System.out.print(str+ " is not a pangram."); 

        } 
    } 

输出应该是真或假,但我没有得到输出

4

5 回答 5

2

Iterator::hasNext检查是否有下一个元素要迭代,但它没有移动到下一个元素。要将迭代器移动到下一个元素,您必须使用Iterator::nextwhich 返回下一个元素。将您的 while 循环更改为:

while (i.hasNext()) {
    count++;
    i.next();
}

在将其转换为 char 数组之前,您必须从中删除空格,String因为 pangrams 不应考虑空格。此外,在创建您的时,Set您应该迭代直到达到 char 数组的长度 - 而不是输入字符串的长度(因为我们将删除空格):

public static boolean checkPangram(String str) {
    int index = 0, count = 0;

    char s[] = str.replaceAll("\\s+","") //remove spaces
            .toCharArray();

    Set<Character> hs = new HashSet<Character>();

    for (index = 0; index < s.length; index++) { //iterate over your charArray
        hs.add(s[index]);
    }

    Iterator<Character> i = hs.iterator();

    while (i.hasNext()) {
        count++;
        i.next();
    }

    return count == 26;  //simplified condition result to be returned

}

但是老实说,您根本不需要迭代器。您可以检查 Set size :

public static boolean checkPangram(String str) {
    char[] s = str.replaceAll("\\s+", "")
                .toCharArray();

    Set<Character> hs = new HashSet<Character>();

    for (int index = 0; index < s.length; index++) {
        hs.add(s[index]);
    }

    return hs.size() == 26;
}
于 2019-07-20T16:31:05.133 回答
2

您需要学习如何调试自己的代码。
请参阅什么是调试器以及它如何帮助我诊断问题?

为什么它返回错误?
因为count是27。

为什么是count = 27
因为你也计算空间。

我该如何解决?
在添加Character.isLetter(s[index])hs.
请参阅 javadoc Characterhttps ://docs.oracle.com/javase/8/docs/api/java/lang/Character.html

另请注意,您不想将大写字母与小写字母视为不同,因此您应该toLowercase()以以下两种方式之一调用 eg :

char s[]=str.toLowercase().toCharArray()

或者:

hs.add(Character.toLowercase(s[index]));
于 2019-07-20T17:01:07.477 回答
0

您的代码中有一些错误需要纠正。

str.toCharArray() 也会在 char s[] 中加入空格。因此计数将是 27,包括空格。相反,您可以在放入 HashSet 之前检查空格。也不需要使用 while 循环,因为我们可以直接获取 HashSet 大小。但是在您的代码块中,您正在使用带有迭代器的 while 循环,因此 i.hasNext() 将始终为真,因此执行将进入无限循环。为避免这种情况,您需要使用 i.next()。

看看下面的代码,你就明白了。

package problems;

import java.util.HashSet;
import java.util.Set;

public class StringCompareTo {

    public static boolean checkPangram(String str) {
        int index = 0;
        char s[] = str.toCharArray();
        Set<Character> hs = new HashSet<Character>();
        for (index = 0; index < str.length(); index++) {
            if(!Character.isWhitespace(s[index]))
            hs.add(s[index]);
        }
        if (hs.size() == 26)
            return true;
        return false;
    }

    // Driver Code
    public static void main(String[] args) {
        String str = "the quick brown fox jumps over the lazy dog";

        if (checkPangram(str) == true)
            System.out.print(str + " is a pangram.");
        else
            System.out.print(str + " is not a pangram.");

    }
}

使用带有迭代器的 while 循环应该是:

Iterator<Character> i = hs.iterator();
        while(i.hasNext()){
        char temp = i.next();
          count++;
        }
于 2019-07-20T17:19:11.303 回答
0

我认为这是一个练习,但你唯一的规定是不要使用 set。你也可以这样做。 并不是真的Streams,而是自 Java 8 以来一直存在的。lambdasadvanced conceptsadditional features

       String str = "the quick brown fox jumps over the lazy dog";
       System.out.println("The string is " + (isPangram(str) ? ""
                : "not ") + "a pangram.");
       }
       public static boolean isPangram(String str) {
          return Arrays.stream(str.split("")).filter(
                a -> a.matches("[A-Za-z]")).distinct().count() == 26;

       }

它消除了除上下字符之外的所有字符,然后将它们放入流中并过滤掉重复项。然后它计算它们。如果计数等于 26,则为 pangram。

于 2019-07-20T18:42:32.047 回答
0
public static void main(String[] args){

String pangramTxt="The quick brown fox jumps over the lazy dog";
checkPangram(pangramTxt);


}

public static void checkPangram(String rawTxt){
    HashSet<Character> set=new HashSet<>();
    //remove nonword characters eg space etc
    
    char[] charArr=rawTxt.replaceAll("\\W+","").toLowerCase().toCharArray();
    
    for(Character val: charArr){
        set.add(val);
    }
    
    //26 ... the alphabet
    if(set.size()==26){
     System.out.println("Text is pangram: ************");
    }

}
于 2020-11-25T18:10:05.010 回答