快乐的字符串
[题目链接](https://www.nowcoder.com/practice/7f4875507c654debb8e02084edbc4fd7)
思路
本题是一道简单的字符串匹配题。给定一个字符串 ,判断其中是否包含以下四个子串之一:
cheerfulgladhappypleased
只要包含任意一个,就输出 Yes,否则输出 No。
做法
直接使用语言内置的子串查找函数即可:
- C++ 中用
string::find,返回值不等于string::npos表示找到; - Java 中用
String.contains; - Python 中用
in运算符; - JavaScript 中用
String.includes。
对每个测试用例依次检查四个目标子串,任一匹配即可判定为"快乐的"。
复杂度分析
设字符串长度为 ,目标子串个数为常数
,最长目标子串长度为常数
。
- 时间复杂度:
,每次子串查找为
,共查找
次。
- 空间复杂度:
,存储输入字符串。
代码
#include <iostream>
#include <string>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
string s;
cin >> s;
if (s.find("cheerful") != string::npos ||
s.find("glad") != string::npos ||
s.find("happy") != string::npos ||
s.find("pleased") != string::npos) {
cout << "Yes" << endl;
} else {
cout << "No" << endl;
}
}
return 0;
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t-- > 0) {
String s = sc.next();
if (s.contains("cheerful") || s.contains("glad") ||
s.contains("happy") || s.contains("pleased")) {
System.out.println("Yes");
} else {
System.out.println("No");
}
}
}
}
t = int(input())
for _ in range(t):
s = input()
if "cheerful" in s or "glad" in s or "happy" in s or "pleased" in s:
print("Yes")
else:
print("No")
const readline = require('readline');
const rl = readline.createInterface({ input: process.stdin });
const lines = [];
rl.on('line', line => lines.push(line.trim()));
rl.on('close', () => {
const t = parseInt(lines[0]);
for (let i = 1; i <= t; i++) {
const s = lines[i];
if (s.includes("cheerful") || s.includes("glad") ||
s.includes("happy") || s.includes("pleased")) {
console.log("Yes");
} else {
console.log("No");
}
}
});

京公网安备 11010502036488号