1243. 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.

the string does not contain any non-printable characters.

您在真實的面試中是否遇到過這個題?  

樣例

Example:

Input: "Hello, my name is John"
Output: 5

這道題判斷的方式是,如果第一個字母不爲空格或者前一個是空格,自己不是空格。

class Solution {
public:
    /**
     * @param s: a string
     * @return: the number of segments in a string
     */
    int countSegments(string &s) {
        // write yout code here
        int count=0;
        for(int i=0;i<s.length();i++){
            if(s[i]!=' '&&(i==0||s[i-1]==' '))
                count++;
        }
        return count;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章