Swift, let array=string.components(separatedBy:" ")


  • 0
    X
    class Solution {
        func lengthOfLastWord(_ s: String) -> Int {
            if s.characters.count <= 1 { return (s=="" || s==" ") ? 0 : 1 } 
    
            let arr = s.components(separatedBy: " ")
            var lastWd = arr.count - 1
            while lastWd >= 0, arr[lastWd].characters.count == 0 { lastWd -= 1 }
            return (lastWd >= 0) ? arr[lastWd].characters.count : 0
        }
    }
    

    There shooould be an easier way to do this in Swift, yet I didnot find the func ...


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.