748. 最短补全词 | 字符串的模拟题

力扣打卡:748. 最短补全词

解题思路

字符串的模拟题

  • 先将字符串 licensePlate 映射到数组上,得到需要的字符数量
  • 设置最长长度是 Integer.MAX_VALUE
  • 对字符串数组的每一个元素进行遍历
  • 统计字符串数组中每一元素的字符数量
  • 比较字符串数组的每一个元素的字符数量和 licensePlate
  • 如果不满足那么跳转判断下一个字符串数组的元素
  • 如果满足条件
    • 判断长度是否符合要求
    • 符合要求更新 anslen
  • 返回 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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值