校招算法笔面试 | 华为机试-字符串字符匹配

题目

题目链接

解题思路

这是一个字符串匹配问题,需要判断短字符串中的所有字符是否都在长字符串中出现。可以使用哈希表来优化时间复杂度。

  1. 读取输入:

    • 读取短字符串S和长字符串T
    • 确保输入的字符串长度在1到200之间
  2. 使用哈希表优化:

    • 将长字符串T中的所有字符存入哈希表
    • 遍历短字符串S中的每个字符,在哈希表中查找
  3. 判断结果:

    • 如果所有字符都能找到,输出"true"
    • 如果有任何字符找不到,输出"false"

代码

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main() {
    string s, t;
    cin >> s >> t;
    
    // 将长字符串的字符存入哈希表
    vector<bool> mp(26);
    for(char c : t) {
        mp[c - 'a'] = true;
    }
    
    // 检查短字符串的每个字符是否在哈希表中
    bool found = true;
    for(char c : s) {
        if(!mp[c - 'a']) {
            found = false;
            break;
        }
    }
    
    cout << (found ? "true" : "false") << endl;
    return 0;
}
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String s = sc.nextLine();
        String t = sc.nextLine();
        
        // 将长字符串的字符存入哈希表
        boolean[] mp = new boolean[26];
        for(char c : t.toCharArray()) {
            mp[c - 'a'] = true;
        }
        
        // 检查短字符串的每个字符是否在哈希表中
        boolean found = true;
        for(char c : s.toCharArray()) {
            if(!mp[c - 'a']) {
                found = false;
                break;
            }
        }
        
        System.out.println(found ? "true" : "false");
    }
}
s = input()
t = input()

# 将长字符串转换为字符集合
char_set = set(t)

# 检查短字符串的每个字符是否在集合中
result = all(c in char_set for c in s)
print("true" if result else "false")

算法及复杂度

  • 算法:哈希表
  • 时间复杂度: O ( n ) \mathcal{O}(n) O(n) - 其中 n n n 是两个字符串的总长度,构建哈希表和查找都是 O ( 1 ) O(1) O(1) 操作
  • 空间复杂度: O ( n ) \mathcal{O}(n) O(n) - 需要哈希表存储长字符串中的字符
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值