Advertisement
halaluddin

Remove-Palindromic-Subsequence

Jun 8th, 2022
1,265
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.16 KB | None | 0 0
  1. class Solution {
  2.    
  3.     /// Find the minimum number of steps(remove palindromic subsequence) to make the string empty.
  4.     ///
  5.     /// - parameters:
  6.     ///  - input: The `String` consisting only letters `a` and `b`.
  7.     /// - returns: return value would be `true` if is it palinmrome string nor `false`
  8.     func removePalindromeSub(_ s: String) -> Int {
  9.         return isPalindrome(s) ? 1 : 2
  10.     }
  11.    
  12.     /// Identify a palindrome string. Complexity: O(n)
  13.     /// - parameters:
  14.     ///  - input: The `String` consisting only letters `a` and `b`.
  15.     /// - returns: return value would be `true` if is it palinmrome string nor `false`
  16.     func isPalindrome(_ input: String) -> Bool {
  17.         guard input.count > 1 else { return true }
  18.         var lhs = 0; var rhs = input.count - 1
  19.  
  20.         while lhs < rhs {
  21.             guard input[lhs] == input[rhs] else { return false }
  22.  
  23.             lhs += 1; rhs -= 1;
  24.         }
  25.  
  26.         return true
  27.     }
  28. }
  29.  
  30. /// The extension subscript making accessable a String using index(like: `s[index]`).
  31. extension StringProtocol {
  32.     subscript(_ offset: Int) -> Element { self[index(startIndex, offsetBy: offset)]}
  33. }
  34.  
  35.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement