swift, use 1 pointer to count non-space words


  • 0
    X

    firstly I try s.components(separatedBy:).count yet got a bug:

        // return (s.characters.count==0) ? 0 : s.components(separatedBy: " ").count
        // BUG: in case "        ", should return 1, yet got s.characters.count
    

    then try to use pointer:

    class Solution {
        func countSegments(_ s: String) -> Int {
            let arr = Array(s.characters)
            let len = arr.count
            if len == 0 { return 0 }
            if len == 1 { return (arr[0]==" ") ? 0 : 1 }
            
            var wordNum = 0, i = 0
            while i < len {
                if arr[i] != " " {
                    wordNum += 1   // at the 1st letter of word, then
                    while i < len, arr[i] != " " { i += 1 } // skip entire word;
                }else{
                    i += 1
                }
            }
            return wordNum
        }
    }
    

Log in to reply
 

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