【问题标题】:How do I find the letters of a certain word within a Character array in Java?如何在 Java 中的字符数组中找到某个单词的字母?
【发布时间】:2014-12-05 02:05:36
【问题描述】:

我需要比较两个不同字符数组中的字符来找到用户输入的隐藏词。

目标是输入 2 个字符串并在另一个字符串中找到一个打乱的单词。 前任。 “tot”这个词在“tomato”这个词中被打乱了

在论坛一些人的帮助下,我实现了字符数组来存储用户字符串,但我不知道如何检查每个数组中所需的字符。我已经尝试了下面的代码,但它总是导致程序无法找到这个词。如果有人能提供更好的方法或解决方案,我将不胜感激。

public static void main(String[] args) {
    input = new Scanner(System.in);

    System.out.println("Please enter a word"); 
    String word = input.next();
    char[] charOfWrds = word.toCharArray();

    System.out.println("Please enter a hidden word you would like to search for");
    String search = input.next();
    char[] charOfSrch = search.toCharArray();

    if (isContains(charOfWrds, charOfSrch))   
    { 
        System.out.print("The word " + search + " is found in the word " + word);
    } 
    else 
    {
        System.out.print("The word was not found in " + word); 
    }
}
public static Boolean isContains(char[] charOfWrds, char[] charOfSrch) {
    int count = 0;
    for (char cha : charOfWrds) 
    {
        for (char chaaa : charOfSrch) 
        {
            if (cha == chaaa)
                count++;
        }
    }
    if (count == charOfSrch.length)
    {
        return true;
    }
    return false;
}

【问题讨论】:

  • 问题陈述/示例没有解释您所说的“加扰”是什么意思。 “番茄”中的“tam”字是不是乱码???

标签: java arrays string loops compare


【解决方案1】:
public static Boolean isContains(char[] charOfWords, char[] charOfSrch) {
    List<Character> searchFor = new ArrayList<>();
    List<Character> searchMe=new ArrayList<>();
    for(char c:charOfWords)
        searchFor.add(c);
    for(char c:charOfSrch)
        searchMe.add(c);

    for(int x=searchFor.size()-1;x>=0;x--){
        if(searchMe.contains(searchFor.get(x)){
            searchMe.remove(searchFor.get(x));
            searchFor.remove(x);//line A
        }                
    }
    return searchFor.size()==0;
}

快速概述它的作用。我将两个字符数组都转换为列表,以便可以使用列表方法。然后,我遍历了单词中你需要查找的每个字符,如果我能在另一个单词中找到它,我将它从两个单词中删除,这意味着如果所有单词都从需要查找的单词中删除,在另一个词中找到了这个词;否则它不是。

我假设您不能在第二个单词中重复使用字母,但如果可以,请删除 A 行。

【讨论】:

  • 感谢您的响应我尝试实现您的代码,但在 if 语句中,有一个错误说“方法 charAt(int) 未定义 List 类型”如何我解决了这个问题?
  • 对不起,我混淆了 String 和 List 方法。您应该使用 searchFor.get(x),而不是 searchFor.charAt(x)。我编辑了答案。
  • 我修复了它,错误消失了,但我需要切换搜索列表,因为一开始输出颠倒了,但现在可以正常工作了!非常感谢您的帮助!
【解决方案2】:

您应该尝试正则表达式而不是尝试编写算法。 使用用户输入构建表达式,然后匹配所需的单词。

【讨论】:

    【解决方案3】:

    采取

    番茄作为 charOfWrds

    tot 为 charOfSrch

    isContains 将计数 6,因为当您在第二个单词中找到第一个单词的字母时,您不会退出。

    t : 两次

    o : 两次

    t : 两次

    试试这个:

    if (cha == chaaa){
        count++;
        break;
    }
    

    但是要完成这项工作,您需要从第二个字符串中删除该字母,因为如果您要查找的单词是“tttt”,那么即使不是,此代码也会为您提供 true,但如果您当你找到它时删除它,那么它应该可以解决问题。

    我不知道你是否足够清楚。

    这里是代码:

    public static Boolean isContains(char[] charOfWrds, char[] charOfSrch) {
        int count = 0;
        for (int i=0; i<charOfWrds.length;i++){
            for (int j=0;j<charOfSrch.length;j++){
                if (charOfWrds[i] == charOfSrch[j]){
                    count++;
                    charOfSrch[j]=' ';
                    break;
                }
            }
        }
        if (count == charOfSrch.length)
        {
            return true;
        }
        return false;
    }
    

    它的工作,我试过这个:

    String word = "tomato";
    char[] charOfWrds = word.toCharArray();
    
    
    String search = "tot";
    char[] charOfSrch = search.toCharArray();
    

    但这很丑,你应该尝试使用java Api,除非你真的必须用数组来做。

    【讨论】:

      【解决方案4】:

      我的想法与@kirbyquerby 提供的类似,只是它有一些优化。

      我们没有使用线性搜索,而是在将每个单词(针和大海捞针)转换为列表后,对这些列表进行排序。这允许我们使用二分搜索,将搜索复杂度从 O(n^2) 更改为 O(n log n)。

      此外,没有必要从针列表中删除字符,因为我们可以跟踪找到了多少针字符。完成搜索后,我们只需将找到的针字符数与针字符总数进行比较。如果它们相等,我们就找到了我们的针。最后,如果没有找到针字符,我们可以立即停止搜索,因为我们知道大海捞针中不存在整个针。

      package hiddenword;
      
      import java.util.ArrayList;
      import java.util.Collections;
      import java.util.List;
      
      public class HiddenWord {
          public static void main(final String args[]) {
              final String haystack = "Tomato";
              final String needle = "tot";
      
              if (contains(haystack, needle)) {
                  System.out.println(haystack + " contains " + needle);
              } else {
                  System.out.println(haystack + " does not contain " + needle);
              }
          }
      
          private static boolean contains(final String haystack, final String needle) {
              // Convert each word to lowercase and into a List.
              final List<Character> haystackChars = toSortedCharacterList(haystack.toLowerCase());
              final List<Character> needleChars = toSortedCharacterList(needle.toLowerCase());
              int foundNeedleChars = 0;
      
              for (final Character c : needleChars) {
                  // Using sorted lists, our search time is be O(n log n) by using
                  // binary search instead of O(n^2) using linear search.
                  int index = Collections.binarySearch(haystackChars, c);
      
                  // A needle character has been found, remove it from the haystack
                  // and increment the count
                  if (index >= 0) {
                      haystackChars.remove(index);
                      ++foundNeedleChars;
                  }
                  // A needle character was not found. This means that the haystack
                  // doesn't contain every character of the needle and we
                  // can quit early
                  else {
                      return false;
                  }
              }
      
              // If we've found all the needle characters, the needle word exists in
              // the haystack word.
              return foundNeedleChars == needleChars.size();
          }
      
          private static List<Character> toSortedCharacterList(final String input) {
              final List<Character> list = new ArrayList<Character>();
      
              // Convert primitive array to List
              for (final char c : input.toCharArray()) {
                  list.add(c);
              }
      
              // Sort that thang
              Collections.sort(list);
      
              return list;
          }
      }
      

      【讨论】:

        【解决方案5】:

        您可以这样做,而不必将字符串转换为数组,例如:

        static boolean containsScrambled(String word, String search){
            //loop through each character of the word whose characters we are searching for
            for(int x = 0; x<search.length(); x++){
                //find the current character to check
                String c = search.substring(x, x+1);
        
                if(word.indexOf(c) >= 0){
                    //if the character is in the word, remove the first instance of it
                    //as we cannot use that character again
                    word.replaceFirst(c, "");
                }else{
                    //if the character is not in the word, fail and return false
                    return false;
                }
            }
        
            //if we made it here, all of the characters existed, return true
            return true;
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-12-16
          • 2020-03-19
          • 2015-03-01
          • 1970-01-01
          • 1970-01-01
          • 2019-03-08
          • 2011-08-26
          • 2019-09-26
          相关资源
          最近更新 更多