解題思路
文章是題目提供的固定資料,程式需嵌入全文並實際搜尋。
以句點或問號加右雙引號為句尾,去除句子首尾分隔空白但保留句內文字與標點。
比對時把句子中的連續英文字母視為單字並不分大小寫,符合者依文章原序編號輸出。連字號會斷詞,所以web-based能匹配web,website不能。
固定文章長L,時間 O(L+關鍵字長度),空間 O(L)。
Step-by-step animation
教學小例:固定文章斷句與完整單字邊界
步驟 1 / 3
關鍵字directory
逐句檢查固定文章
逐句檢查固定文章
- 步驟
- 1
#include <bits/stdc++.h>
using namespace std;
int main() {
string article =
"ProxEasy serves as a barrier between you and the rest of the internet. "
"All traffic which goes through this web-based proxy server service "
"becomes completely anonymous because it is being bounced through the "
"ProxEasy network. Just like you see on the movies, where hackers "
"bounce their connections through multiple servers to hide their true "
"location, so too does this web proxy server service make you totally "
"untraceable and anonymous on the WWW. It lets you hide your ip from "
"prying eyes. Ever ask yourself \"How do I hide my ip?\" Perhaps you "
"may have been wondering how to access blocked websites that your "
"school or workplace are preventing you from surfing with their filters "
"that block users from getting on certain sites. Well this proxy server "
"will actually allow you to get on those websites with ease, and hide "
"your ip address at the same time. Or check the directory. All you have "
"to do is type in the URL or Web address of the sites you want to visit "
"in the text box above and hit the \"Go\" button. Try ProxEasy now by "
"typing a URL into the website address textbox on the form at the top "
"of the page. I think you will like this web proxy server.",
key;
cin >> key;
for (char &c : key)
c = tolower(c);
vector<string> sentences;
size_t st = 0;
for (size_t i = 0; i < article.size(); i++)
if (article[i] == '.' ||
(article[i] == '?' && i + 1 < article.size() && article[i + 1] == '"')) {
if (article[i] == '?')
i++;
string s = article.substr(st, i - st + 1);
auto a = s.find_first_not_of(" \n\r\t"), b = s.find_last_not_of(" \n\r\t");
sentences.push_back(s.substr(a, b - a + 1));
st = i + 1;
}
int count = 0;
for (auto s : sentences) {
string w;
bool hit = false;
for (size_t i = 0; i <= s.size(); i++) {
char c = i < s.size() ? s[i] : ' ';
if (isalpha((unsigned char)c))
w += tolower(c);
else {
hit |= w == key;
w.clear();
}
}
if (hit)
cout << ++count << ". " << s << '\n';
}
if (!count)
cout << "查無此字\n";
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。