力扣打卡:748. 最短补全词
解题思路
字符串的模拟题
- 先将字符串
licensePlate
映射到数组上,得到需要的字符数量 - 设置最长长度是
Integer.MAX_VALUE
- 对字符串数组的每一个元素进行遍历
- 统计字符串数组中每一元素的字符数量
- 比较字符串数组的每一个元素的字符数量和
licensePlate
- 如果不满足那么跳转判断下一个字符串数组的元素
- 如果满足条件
- 判断长度是否符合要求
- 符合要求更新
ans
和len
- 返回
ans
代码
class Solution {
public String shortestCompletingWord(String licensePlate, String[] words) {
// 遍历字符串,将字符串映射到数组上
int[] line = new int[26];
for(char c : licensePlate.toCharArray()){
if('a'<=c && c<='z'){
line[c-'a']++;
}else if( 'A'<=c && c<='Z' ){
line[c + ('a'-'A')-'a']++;
}
}
String ans = "";
int len = Integer.MAX_VALUE;
for(String s : words){
int[] count = new int[26];
for(char c: s.toCharArray()){
count[c-'a']++;
}
boolean flag = true;
for(int i=0; i<26; i++) {
if(count[i]-line[i] < 0) {flag = false; break;}
}
if(flag && s.length() < len){ // 记录等长的第一个
ans = s;
len = s.length();
}
}
return ans;
}
}