halaluddin

1147. Longest Chunked Palindrome Decomposition - Solution

Nov 8th, 2021 (edited)
255
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 0.99 KB | None | 0 0
  1. /// Swift
  2.  
  3. class Solution {
  4.     func longestDecomposition(_ text: String) -> Int {
  5.         var text = text, leftSubStr = "", rightSubStr = "", ans = 0
  6.         let totalChar = text.count
  7.         let n = Int(totalChar / 2) + 1
  8.        
  9.         for i in 1..<n {
  10.             leftSubStr += String(text.removeFirst())
  11.             rightSubStr = String(text.removeLast()) + rightSubStr
  12.             if leftSubStr == rightSubStr {
  13.                 leftSubStr = ""; rightSubStr = ""
  14.                 ans += 2
  15.             }
  16.         }
  17.        
  18.         /// when last(most middle) pair does not matched.
  19.         if leftSubStr.count != 0 && rightSubStr.count != 0 {
  20.             ans += 1
  21.         }
  22.        
  23.         /// if text count is odd and already matched last previous pair,
  24.         /// then we need to increase 1 for the middle character.
  25.         if (leftSubStr.count == 0 && rightSubStr.count == 0) && totalChar % 2 == 1 {
  26.             ans += 1
  27.         }
  28.        
  29.         return ans
  30.     }
  31. }
Add Comment
Please, Sign In to add comment