2287. 重排字符形成目标字符串

解决代码

class Solution {
    public int rearrangeCharacters(String s, String target) {
        Map<Character, Integer> sCounts = new HashMap<Character, Integer>();
        Map<Character, Integer> targetCounts = new HashMap<Character, Integer>();
        int n = s.length(), m = target.length();
        for (int i = 0; i < m; i++) {
            char c = target.charAt(i);
            targetCounts.put(c, targetCounts.getOrDefault(c, 0) + 1);
        }
        for (int i = 0; i < n; i++) {
            char c = s.charAt(i);
            if (targetCounts.containsKey(c)) {
                sCounts.put(c, sCounts.getOrDefault(c, 0) + 1);
            }
        }
        int ans = Integer.MAX_VALUE;
        for (Map.Entry<Character, Integer> entry : targetCounts.entrySet()) {
            char c = entry.getKey();
            int count = entry.getValue();
            int totalCount = sCounts.containsKey(c) ? sCounts.get(c) : 0;
            ans = Math.min(ans, totalCount / count);
            if (ans == 0) {
                return 0;
            }
        }
        return ans;
    }
}

使用的是hash表解决,我发现使用HashMap真的很频繁

  1. 添加元素
Map<KeyType, ValueType> map = new HashMap<>();

// 添加键为 key,值为 value 的键值对
map.put(key, value);
  1. 获取元素
// 根据键获取对应的值
ValueType value = map.get(key);
  1. 删除元素
// 根据键删除对应的键值对
ValueType removedValue = map.remove(key);

// 清空所有的键值对
map.clear();
  1. 判断是否包含键或值
// 判断是否包含指定的键
boolean containsKey = map.containsKey(key);

// 判断是否包含指定的值
boolean containsValue = map.containsValue(value);
  1. 获取键或值的集合视图
// 获取所有键的集合
Set<KeyType> keys = map.keySet();

// 获取所有值的集合
Collection<ValueType> values = map.values();
  1. 遍历键值对
// 遍历所有的键值对
for (Map.Entry<KeyType, ValueType> entry : map.entrySet()) {
    KeyType key = entry.getKey();
    ValueType value = entry.getValue();
    // 对键值对进行操作
}
  1. 获取键值对的数量
int size = map.size();

字符串

  1. 创建字符串对象

可以使用字符串字面量或使用new关键字来创建字符串对象。字符串字面量是用双引号括起来的字符序列,例如:“Hello World”。使用字符串字面量创建字符串对象时,Java自动将其转换为一个String对象。例如,以下代码创建了一个字符串对象s1:

String s1 = "Hello World";

也可以使用new关键字显式地创建字符串对象,例如:

String s2 = new String("Hello World");
  1. 字符串连接

可以使用+操作符来连接两个字符串,例如:

String s3 = "Hello";
String s4 = "World";
String s5 = s3 + s4; //"HelloWorld"

还可以使用concat()方法连接两个字符串,例如:

String s6 = s3.concat(s4); //"HelloWorld"
  1. 获取字符串长度

可以使用length()方法获取字符串的长度,例如:

String s7 = "HelloWorld";
int len = s7.length(); //10
  1. 获取子字符串

可以使用substring()方法获取一个字符串的子串,例如:

String s8 = "HelloWorld";
String s9 = s8.substring(0, 5); //"Hello"
  1. 查找子字符串

可以使用indexOf()方法查找一个字符串中某个子字符串的位置,例如:

String s10 = "HelloWorld";
int index = s10.indexOf("World"); //5
  1. 替换子字符串

可以使用replace()方法替换一个字符串中某个子字符串,例如:

String s11 = "Hello World";
String s12 = s11.replace("World", "Java"); //"Hello Java"

这些是Java中常见的字符串操作,此外还有很多其他的字符串操作方法,可以查看Java API文档了解更多详情。