434. Number of Segments in a String

/* 
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")
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容