So, I did some testing. In your approach, Test2 is time consuming.
Data: 2000 random 20 lines of characters.
Your solution: 2500 ms. Seth Carnegie's: 500 ms.
Although I believe that you need to multiply them by 2, because s + v can be a palindrome, and v + s isnt.
Idea: suppose we have the word ABCD. In other words, then there can be palindromes with this only cba and dcba. Let's check if we have those present.
... #include <set> using namespace std; bool isPal(const string&); int main() { ... set<string> rWords; ... while(fin){ fin >> str; sWords.push_back(str); if(!fin){ break; } reverse(str.begin(), str.end());//add reversed str to rWords rWords.insert(str); reverse(str.begin(), str.end()); ... } ... // Test 2 for(int i = 0; i<sWords.size(); ++i) for(int l = 0; l<sWords[i].length(); ++l) if(isPal(sWords[i].substr(sWords[i].length()-l))) { string s = sWords[i].substr(0,sWords[i].length()-l); set<string>::iterator it = rWords.find(sWords[i].substr(0,sWords[i].length()-l)); if(it != rWords.end()) { string s = *it; reverse(s.begin(), s.end()); if(s == sWords[i])//isPoly to itself continue; sTwoWords1.push_back(sWords[i]); sTwoWords2.push_back(s); } } ... return 0; } bool isPal(const string& testing) { return std::equal(testing.begin(), testing.begin() + testing.size() / 2, testing.rbegin()); }
time: 15 ms
kilotaras
source share