【问题标题】:simple algorithm to find anagram查找字谜的简单算法
【发布时间】:2019-02-02 08:18:45
【问题描述】:
public class anagrm {
public static void main(String args[]){
    String s1 = new String();
    String s2 = new String();
    int count = 0;
    Scanner sc = new Scanner(System.in);
    s1 = sc.nextLine();``
    s2 = sc.nextLine();
    if(s1.length()==s2.length())
        for (int i = 0; i < s1.length(); i++)
            for (int j = 0; j < s1.length(); j++)
                if (s1.charAt(i) == s2.charAt(j)){
                    count++
                }

    if(count>=s1.length())
        System.out.println("string is anagram");
    else
        System.out.println("string is not anagram");
    System.out.println(count);
}


}

它是真实的军队和马尔..我知道错误在哪里,但我想以这种方式完成......

【问题讨论】:

  • 完全不清楚。错误是什么?什么是预期的输出?请解释更多
  • @ibarrond 他只希望它在 s1 和 s2 是字谜的情况下返回 true,而目前它有时会返回 true,即使它们不是(因为重复字母)。
  • 这可能是真的,但他的任务是在问题中明确说明。否则对于其他搜索它的人来说毫无用处

标签: java anagram


【解决方案1】:

您会遇到错误,因为任何时候一个字母在 s1 中出现不止一次,您每次都会递增计数器,即使 s2 只有该字母一次。解决此问题的一种方法是改用StringBuilder,当您在字母中找到匹配项时,使用deleteCharAt 方法从s2 中删除该字母。为此,您还需要将第二个for 循环更改为循环s2.length,因为它会不断变短。不是那么优雅,但它会起作用。

【讨论】:

    【解决方案2】:

    正如其他人所提到的,无论 s1 有多少次字母,只要字母匹配,您的计数变量就会递增。如果您想使用计数解决方案,那么您应该增加每个字母的计数:

    import java.util.HashMap
    import java.util.Map
    
    /* This is how to declare HashMap */
    HashMap<char, String> s1map = new HashMap<char, String>();
    HashMap<char, String> s2map = new HashMap<char, String>();
    
    for (int j = 0; j < s1.length(); j++){
        //We create 2 hashmaps to count the number of each char in each word separately
        s1map.put(key, s1map.getOrDefault(key, 0) + 1);
        s2map.put(key, s2map.getOrDefault(key, 0) + 1);
    }
    

    最后,您可以将生成的地图与:

    if s1map.equals(s2map){
        print("They are anagrams")
    }
    else{
        print("They are not anagrams")
    }
    

    【讨论】:

      猜你喜欢
      • 2021-10-16
      • 2010-12-01
      • 2012-11-03
      • 2011-02-07
      • 2012-09-10
      • 2011-11-03
      • 2013-09-20
      • 2021-04-21
      • 1970-01-01
      相关资源
      最近更新 更多