题目
我的题解
暴力解法
先统计两个string中字符出现的频率,然后以s字符串为基准,t中对应的字符少多少个答案加一;不用去管t中多出的字符,在前一步比较时相当于改变了t中多余的字符。
class Solution {
public int minSteps(String s, String t) {
char[] sList = new char[s.length()];
int[] sCnt = new int[s.length()];
char[] tList = new char[t.length()];
int[] tCnt = new int[t.length()];
updateList(sList, sCnt, s);
updateList(tList, tCnt, t);
int result = 0;
for (int i = 0; i < sList.length; i++) {
boolean findSame = false;
for (int j = 0; j < tList.length; j++) {
if (sList[i] == tList[j]) {
result = (sCnt[i] > tCnt[j]) ? result + sCnt[i] - tCnt[j] : result;
findSame = true;
break;
}
}
if (!findSame) {
result += sCnt[i];
}
}
return result;
}
public void updateList(char[] list, int[] cnt, String s) {
int j;
list[0] = s.charAt(0);
cnt[0] = 1;
for (int i = 1; i < s.length(); i++) {
boolean findSame = false;
for (j = 0; list[j] != '\0'; j++) {
if (list[j] == s.charAt(i)) {
cnt[j]++;
findSame = true;
break;
}
}
if (!findSame) {
for (int k = 0; k < list.length; k++) {
if (list[k] == '\0') {
list[k] = s.charAt(i);
cnt[k] = 1;
break;
}
}
}
}
}
}
其他题解
暴力解法优化
优化的点:
- 建立列表的长度为26即可,因为是26个字母
- 同时列表的索引为字母在字母表中的位置,避免了后续查找相同字符对应出现次数的再一次遍历
(妙啊,我怎么就想不到呢)
看解法链接中Drinkwater大佬的解答。
总结
- 用
toCharArray
可以把字符串转换成char[]