diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 019. \346\234\200\345\244\232\345\210\240\351\231\244\344\270\200\344\270\252\345\255\227\347\254\246\345\276\227\345\210\260\345\233\236\346\226\207/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 019. \346\234\200\345\244\232\345\210\240\351\231\244\344\270\200\344\270\252\345\255\227\347\254\246\345\276\227\345\210\260\345\233\236\346\226\207/README.md" index c0a79f7477826..d84113c589def 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 019. \346\234\200\345\244\232\345\210\240\351\231\244\344\270\200\344\270\252\345\255\227\347\254\246\345\276\227\345\210\260\345\233\236\346\226\207/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 019. \346\234\200\345\244\232\345\210\240\351\231\244\344\270\200\344\270\252\345\255\227\347\254\246\345\276\227\345\210\260\345\233\236\346\226\207/README.md" @@ -204,6 +204,42 @@ var validPalindrome = function (s) { }; ``` +#### Swift + +```swift +class Solution { + private var s: String = "" + + func validPalindrome(_ s: String) -> Bool { + self.s = s + var i = s.startIndex + var j = s.index(before: s.endIndex) + + while i < j { + if s[i] != s[j] { + return check(s.index(after: i), j) || check(i, s.index(before: j)) + } + i = s.index(after: i) + j = s.index(before: j) + } + return true + } + + private func check(_ i: String.Index, _ j: String.Index) -> Bool { + var i = i + var j = j + while i < j { + if s[i] != s[j] { + return false + } + i = s.index(after: i) + j = s.index(before: j) + } + return true + } +} +``` + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 019. \346\234\200\345\244\232\345\210\240\351\231\244\344\270\200\344\270\252\345\255\227\347\254\246\345\276\227\345\210\260\345\233\236\346\226\207/Solution.swift" "b/lcof2/\345\211\221\346\214\207 Offer II 019. \346\234\200\345\244\232\345\210\240\351\231\244\344\270\200\344\270\252\345\255\227\347\254\246\345\276\227\345\210\260\345\233\236\346\226\207/Solution.swift" new file mode 100644 index 0000000000000..ecb9813b5d150 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 019. \346\234\200\345\244\232\345\210\240\351\231\244\344\270\200\344\270\252\345\255\227\347\254\246\345\276\227\345\210\260\345\233\236\346\226\207/Solution.swift" @@ -0,0 +1,31 @@ +class Solution { + private var s: String = "" + + func validPalindrome(_ s: String) -> Bool { + self.s = s + var i = s.startIndex + var j = s.index(before: s.endIndex) + + while i < j { + if s[i] != s[j] { + return check(s.index(after: i), j) || check(i, s.index(before: j)) + } + i = s.index(after: i) + j = s.index(before: j) + } + return true + } + + private func check(_ i: String.Index, _ j: String.Index) -> Bool { + var i = i + var j = j + while i < j { + if s[i] != s[j] { + return false + } + i = s.index(after: i) + j = s.index(before: j) + } + return true + } +} \ No newline at end of file