【问题标题】:Java - check if a string is a subset of another string [closed]Java - 检查一个字符串是否是另一个字符串的子集[关闭]
【发布时间】:2020-12-05 14:42:53
【问题描述】:

我正在尝试实现一个函数,它检查一个字符串是否是另一个字符串的子集。

例如,“lig”是“light”的子集。

“gil”也是“light”的子集。

但“liig”不是“light”的子集。

我什么都试过了,for循环,嵌套for循环,if,else...

我将感谢您对此的帮助!非常感谢! :)

【问题讨论】:

  • if("light".contains("lig")) {//...}
  • 能否请您展示一下您尝试过的内容
  • 您能解释一下子集是什么意思吗?如果字符串 s1 可以由字符串 s2 的字符创建,您的意思是字符串 s1 是 s2 的子集吗?字符串 s2 的字符顺序是否应该与字符串 s1 相同?
  • 感谢您的 cmets!我的意思是第一个字符串的字母也必须在第二个字符串中,而顺序无关紧要。我创建了一个函数来计算字符在字符串中出现的次数,并尝试使用它,但没有成功。
  • 您熟悉地图吗?如果是,则创建一个映射,该映射将计算每个字符串中存在多少重复字符,例如 abbc -> a:1 b:2 c:1 然后对其他字符串执行相同操作,例如 ba a:1 b:1 .现在你只需要检查来自“子集”的字母是否存在,如果映射代表“超集”并且不超过超集中的数量。

标签: java string substring subset


【解决方案1】:

您可以使用Hashmap 和 cmets 中描述的一些简单操作来执行此操作:

import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        System.out.println(isSubset("light", "lig"));
        System.out.println(isSubset("light", "gil"));
        System.out.println(isSubset("light", "liig"));
    }
    private static boolean isSubset(String str, String sub) {
        // change strings to lower case
        str = str.toLowerCase();
        sub = sub.toLowerCase();
        // initialze hashmap to store character frequencies in substring
        Map<Character, Integer> map = new HashMap<>();
        // iterate over the substring and store number of occurrences per character
        for(char c : sub.toCharArray()) {
            Integer count = map.get(c);
            map.put(c, count!=null ? count+1 : 1);
        }
        // iterate over the original string and decrement the count of each character present in the map
        for(char c : str.toCharArray()) {
            Integer count = map.get(c);
            if(count!=null)
                map.put(c, count-1);
        }
        // check if all characters count has reached to zero, i.e., present in the string
        for(int count : map.values())
            if(count != 0)
                return false;
        return true;
    }
}

输出:

true
true
false

【讨论】:

  • 谢谢!不幸的是,我不熟悉 StringBuilder、toString 或 Reverse。我正在尝试使用简单的方法。
  • 感谢您的宝贵时间!我想我会在几周内了解您在这里所做的事情,所以我会在我了解后再次阅读。
猜你喜欢
  • 2019-05-11
  • 1970-01-01
  • 2013-05-12
  • 2011-02-07
  • 2022-07-01
  • 2020-10-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多