Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /// Swift
- class Solution {
- func longestDecomposition(_ text: String) -> Int {
- var text = text, leftSubStr = "", rightSubStr = "", ans = 0
- let totalChar = text.count
- let n = Int(totalChar / 2) + 1
- for i in 1..<n {
- leftSubStr += String(text.removeFirst())
- rightSubStr = String(text.removeLast()) + rightSubStr
- if leftSubStr == rightSubStr {
- leftSubStr = ""; rightSubStr = ""
- ans += 2
- }
- }
- /// when last(most middle) pair does not matched.
- if leftSubStr.count != 0 && rightSubStr.count != 0 {
- ans += 1
- }
- /// if text count is odd and already matched last previous pair,
- /// then we need to increase 1 for the middle character.
- if (leftSubStr.count == 0 && rightSubStr.count == 0) && totalChar % 2 == 1 {
- ans += 1
- }
- return ans
- }
- }
Add Comment
Please, Sign In to add comment