【问题标题】:Find All Anagrams in a String code not working在字符串代码中查找所有字谜不起作用
【发布时间】:2021-09-14 05:07:32
【问题描述】:

Input link for which it is failing

对于给定的问题陈述,我提出了以下解决方案,但在 leetcode 中的一个输入却失败了。

class Solution {    
  public List<Integer> findAnagrams(String s, String p) {
    List<Integer> list = new ArrayList<Integer>();
    int k = p.length();
    Map<Character, Integer> m1 = new HashMap<Character, Integer>();// hash map for string p
    Map<Character, Integer> m2 = new HashMap<Character, Integer>();//hash map for string s 
    
    for (int i = 0; i < p.length(); i++) {
      Character c = p.charAt(i);
      if (m1.containsKey(c)) {
        m1.put(c, m1.get(c) + 1);
      } else {
        m1.put(c, 1);
      }
    }
    int i = 0, j = 0;
    while (j < s.length()) {
      Character c = s.charAt(j);
      if (m2.containsKey(c)) {
        m2.put(c, m2.get(c) + 1);
      } else {
        m2.put(c, 1);
      }

      if (j - i + 1 == k) {
        boolean isAnagram = true;
        for (int m = 0; m < p.length(); m++) {
          if (m1.get(p.charAt(m)) != m2.get(p.charAt(m))) {
            isAnagram = false;
            break;
          }
        }
        if (isAnagram) {
          list.add(i);
        }
        m2.put(s.charAt(i), m2.get(s.charAt(i)) - 1);
        i++;
        j++;
      } else if (j - i + 1 < k) {
        j++;
      }
    }
    return list;
  }
}

我还确认,当 i = 0 时,a 出现的哈希图中的值为 10000,但它仍然进入“if”块并将“isAnagram”变量设置为“false”。你能告诉我为什么会这样吗?

【问题讨论】:

  • 整数 != int.我不确定那是问题所在,但你应该使用 equals !由于它是两个整数,我很确定不会进行拆箱...
  • 使用这两个 if(!m2.containsKey(c1) || m1.get(c1).intValue()!=m2.get(c1).intValue()) 或 if( !m2.containsKey(p.charAt(m)) || (int)m1.get(p.charAt(m))!=(int)m2.get(p.charAt(m)))

标签: java string algorithm data-structures sliding-window


【解决方案1】:

我能够通过使用此条件 if(!m2.containsKey(p.charAt(m)) || (int)m1.get(p.charAt(m))!=(int)m2 来解决它。得到(p.charAt(m)))

if(!m2.containsKey(c1) || m1.get(c1).intValue()!=m2.get(c1).intValue())

【讨论】:

    猜你喜欢
    • 2011-02-03
    • 2020-11-08
    • 2019-05-16
    • 2017-01-16
    • 2014-04-13
    • 1970-01-01
    • 2020-07-04
    • 2016-08-20
    • 2017-08-14
    相关资源
    最近更新 更多