美文网首页LeetCode
434. Number of Segments in a Str

434. Number of Segments in a Str

作者: 小万叔叔 | 来源:发表于2017-01-09 10:08 被阅读10次
    /* 
    Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters.
    
    Please note that the string does not contain any non-printable characters.
    
    Example:
    
    Input: "Hello, my name is John"
    Output: 5
    */
    
    /*
     Thinking: 
     1. 要考虑头尾空格的问题
     2. 要考虑没有空格的问题
     3. 要考虑中间多个空格的问题
     综合以上如果
     
     空格即为比较元素,字符串对于分割体来说,只存在两种元素,
     非空格,空格
     
     _----_----__-----
     符合这种0,1信号的问题,从0到1算作一个section,1降到0不计入,
     也可以理解为波峰波谷之间的关系抽象
     
    */
    
    enum SecmentsStatus: String {
        case Space = " "
        case Other = "o"
        
        //切换状态,返回是否切换
        mutating func switchStatus(_ str: String) -> Bool {
            //把输入的子串转换对两种模式
            let covertStr = (str == SecmentsStatus.Space.rawValue) ? SecmentsStatus.Space : SecmentsStatus.Other
            
            //与当前状态相同,则不做改变
            if covertStr == self {  //相同直接返回,不做改变
                return false
            }
            
            //不同,则做切换
            switch self {
                case .Space:
                    self = SecmentsStatus.Other
                    return true
                
                case .Other:
                    self = SecmentsStatus.Space
                    return false
                
            }
        }
    }
    
    func secments(In str: String) -> Int {
        
        var beforeCharacter = SecmentsStatus.Space
        
        var count = 0
        for character in str.characters {
            //发生了切换则+1
            if beforeCharacter.switchStatus(String(character)) {
                count += 1
            }
        }
        
        return count
    }
    
    secments(In: "")
    secments(In: "ab")
    secments(In: "ab cd")
    secments(In: "cd ef, defgh")
    secments(In: "abc, def")
    

    相关文章

      网友评论

        本文标题:434. Number of Segments in a Str

        本文链接:https://www.haomeiwen.com/subject/sbgcbttx.html