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;
}
}
2条答案
按热度按时间uidvcgyl1#
你可以使用
Hashmap
以及评论中描述的一些简单操作:输出:
vlurs2pr2#
改用substring()方法