[英]Cannot find a logical sense
我已經在學校學習了 c++,在最后幾天我一直在學習 codecademy 的初學者 c++ 課程。 在 codecademy 上有一個練習,我必須識別回文詞並返回真或假。 我無法解決它,所以我看到了解決方案,它是:
#include <iostream>
// Define is_palindrome() here:
bool is_palindrome(std::string text) {
std::string reversed_text = "";
for (int i = text.size() - 1; i >= 0; i--) {
reversed_text += text[i];
}
if (reversed_text == text) {
return true;
}
return false;
}
int main() {
std::cout << is_palindrome("madam") << "\n";
std::cout << is_palindrome("ada") << "\n";
std::cout << is_palindrome("lovelace") << "\n";
}
我唯一的疑問是這一行:
for (int i = text.size() - 1; i >= 0; i--) {
reversed_text += text[i];
我知道它與索引值有關,但我不明白為什么它有一個-1。 有人可以向我解釋一下嗎?
我提前感謝閱讀這篇文章的人。 我很抱歉我的英語或我對 stacksoverflow 的使用不佳,我是意大利人,這是我第一次使用這個網站。
我知道它與索引值有關,但我不明白為什么它有一個-1。
如果字符串的長度為n 個字符,則其中的字符索引從 0 到n -1。
由於循環處理從字符串末尾到開頭的字符,因此它以索引text.size() - 1
開始。
但是,您展示的解決方案名義上效率低下。 沒有理由制作字符串的反向副本。 只需測試字符串前半部分中的每個字符是否等於反射位置中的字符就足夠了:
bool is_palindrome(std::string text)
{
size_t e = text.size();
for (int i = 0; i < e/2; ++i)
if (text[i] != text[e-1-i])
return false;
return true;
}
for (int i = text.size() - 1; i >= 0; i--) {
reversed_text += text[i];
text基本上是您通過函數作為輸入接收到的字符串。 size()是返回字符串大小的函數,即text.size()所以在我們的測試用例中它將返回
如果您將字符串視為具有精確以上大小的數組,則索引范圍將變為
這就是為什么text.size()-1用作循環的起始索引的原因。 text.size()將返回字符串的實際大小,然后減去 1以獲取字符串中最后一個字符的索引。
所以在幕后,您的循環迭代將如下所示
for (int i = 4; i >= 0; i--) { //for madam
}
//aca
for (int i = 2; i >= 0; i--) {
}
//lovelace
for (int i = 7; i >= 0; i--) {
}
我希望它能消除你的困惑。
謝謝,
如果使用 for 循環反轉字符串令人困惑,您也可以使用 reverse 函數
std::string reversed_text = text;
reverse(reversed_text.begin(),reversed_text.end());
這只是有助於翻轉整個字符串reversed_text
並且可以以更簡單的方式實現相同的結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.