我正在練習Koeing加速C++,並想驗證我的答案。由於網上沒有可用的解決方案,我想在這裏發佈,並請專家查看我的解決方案。我不確定人們是否會喜歡我在這裏發佈。如果沒有,請讓我知道,我將來不會這樣做。此外,它不是作業,它完全是我希望將我的C++技能提升到更高水平的願望。加速C++尋找最長的迴文
問題:編寫一個程序來查找字典中的所有迴文。接下來,找到最長的迴文。
我到目前爲止所做的工作 - >我定義了測試迴文的函數,也將所有單詞存儲在一個列表中。我已經在下面發佈了我的代碼。
我卡在哪裏:我需要建議,無論我選擇使用列表數據結構而不是使用列表數據結構嗎?其次,我堅持如何顯示最長的單詞。我可以顯示最長的字,但不是最長的字。
我嘗試下面
bool palindromeTest(const std::string& input)
{
typedef std::string::size_type strSize;
strSize i = 0;
strSize j = input.size() - 1 ;
while(i < input.size())
{
if (input[i] != input[j])
{
return false;
}
i++;
j--;
}
return true;
}
int main()
{
// stores all words in a list or vector
std::list< string> listDict;
std::string readWord;
std::ifstream readFile("/Users/apple/palidndrome-ch5-10/dict.txt");
if(! readFile)
{
std::cout <<" failed to open file" << std::endl;
return 0;
}
while(readFile >> readWord)
{
listDict.push_back(readWord);
}
std::string::size_type maxLen = 0 ;
std::string longestWord = " "; // to store longest palindrome
// print all the palindrome words and also which is longest palindrome.
for(std::list<std::string>::const_iterator it = listDict.begin(); it != listDict.end(); ++it)
{
if(palindromeTest(*it) )
{
std::cout <<" the word -> " << *it << " is palindrome" << std::endl;
// find max len of palindrome;
maxLen = max(maxLen, it->size());
longestWord = *it ;// need to change code here ?? no idea how
}
}
std::cout <<" the maximum len is = " << maxLen << std::endl;
std::cout << " the word with maximum length is " << longestWord ; // something is wrong here
return 0;
}
我想指出通過在閱讀時檢查每個單詞,而不是將它們全部存儲到一個巨大的容器中,可以節省多少內存呃。 – chris 2012-07-15 03:21:39
@chris,請你詳細說明你的意思。我對C++很陌生。我沒有明確指定任何內存。我需要爲記憶做些什麼? – samantha 2012-07-15 03:26:14
我的意思是這個:假設你的字典是100k字。你現在做的方式是將它們全部存儲到列表中。如果每個元素是指向字符的指針的4個字節,那麼列表中就有400K的內存(沒有實際的字)。現在一次一個地使用一個字符串來保存當前的一個字節需要4個字節,但是你需要做的是檢查它是否是迴文,檢查它是否是迄今爲止最長的,然後繼續。現在400K可能並不重要,但最終你可能會陷入這樣的情況,你可以節省很多這樣的數額。 – chris 2012-07-15 03:31:42