1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
|
#include <bits/stdc++.h>
#define endl '\n'
#define int long long
using namespace std;
// 字符串分割
vector<string> split(const string& s, char delimiter)
{
vector<string> tokens;
string token;
istringstream tokenStream(s);
while (getline(tokenStream, token, delimiter))
{
tokens.push_back(token);
}
return tokens;
}
// 检查字符串前缀
bool starts_with(const string& s, const string& prefix)
{
return s.size() >= prefix.size() && s.compare(0, prefix.size(), prefix) == 0;
}
// 检查字符串后缀
bool ends_with(const string& s, const string& suffix)
{
return s.size() >= suffix.size() && s.compare(s.size() - suffix.size(), suffix.size(), suffix) == 0;
}
// 检查字符串包含
bool contains(const string& s, const string& substr)
{
return s.find(substr) != string::npos;
}
// 回文串判断
bool is_palindrome(const string& s)
{
int left = 0, right = s.size() - 1;
while (left < right)
{
if (s[left] != s[right])
{
return false;
}
left++;
right--;
}
return true;
}
// KMP 算法
vector<int> kmp_search(const string& text, const string& pattern)
{
vector<int> result;
int n = text.size(), m = pattern.size();
if (m == 0) return result;
vector<int> lps(m, 0);
for (int i = 1, len = 0; i < m; )
{
if (pattern[i] == pattern[len])
{
lps[i++] = ++len;
}
else if (len > 0)
{
len = lps[len - 1];
}
else
{
lps[i++] = 0;
}
}
for (int i = 0, j = 0; i < n; )
{
if (pattern[j] == text[i])
{
i++;
j++;
if (j == m)
{
result.push_back(i - j);
j = lps[j - 1];
}
}
else if (j > 0)
{
j = lps[j - 1];
}
else
{
i++;
}
}
return result;
}
signed main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
// 读取字符串
string s;
getline(cin, s);
// 分割
vector<string> tokens = split(s, ' ');
for (const string& token : tokens)
{
cout << token << endl;
}
// 检查回文
string palindrome_candidate = "racecar";
if (is_palindrome(palindrome_candidate))
{
cout << palindrome_candidate << " is a palindrome" << endl;
}
// KMP 查找
string text = "ABABDABACDABABCABAB";
string pattern = "ABABCABAB";
vector<int> positions = kmp_search(text, pattern);
cout << "Pattern found at positions: ";
for (int pos : positions)
{
cout << pos << " ";
}
cout << endl;
// C++11 字符串检查
string test = "Hello, C++11!";
if (starts_with(test, "Hello"))
{
cout << "Starts with Hello" << endl;
}
if (ends_with(test, "!"))
{
cout << "Ends with !" << endl;
}
if (contains(test, "C++"))
{
cout << "Contains 'C++'" << endl;
}
return 0;
}
|