解题思路

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

  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")

算法及复杂度

  • 算法:哈希表
  • 时间复杂度: - 其中 是两个字符串的总长度,构建哈希表和查找都是 操作
  • 空间复杂度: - 需要哈希表存储长字符串中的字符