From 47309497162a33617b6a045e45c648fc6e474b07 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 17 Sep 2017 16:34:09 +0800 Subject: [PATCH] Create valid-palindrome-ii.cpp --- C++/valid-palindrome-ii.cpp | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 C++/valid-palindrome-ii.cpp diff --git a/C++/valid-palindrome-ii.cpp b/C++/valid-palindrome-ii.cpp new file mode 100644 index 000000000..1cd239064 --- /dev/null +++ b/C++/valid-palindrome-ii.cpp @@ -0,0 +1,27 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + bool validPalindrome(string s) { + int left = 0, right = s.length() - 1; + while (left < right) { + if (s[left] != s[right]) { + return validPalindrome(s, left, right - 1) || validPalindrome(s, left + 1, right); + } + ++left, --right; + } + return true; + } + +private: + bool validPalindrome(const string& s, int left, int right) { + while (left < right) { + if (s[left] != s[right]) { + return false; + } + ++left, --right; + } + return true; + } +};