434.Number of Segments in a String(String-Easy)

转载请注明作者和出处: http://blog.csdn.net/c406495762

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

题目:返回字符串有几个字段。

思路:很简单,空格就是区分字段的标志。

  • 自己写个trim()函数,用于去掉字符串两端的空格;
  • 判断字符串是会否为空,为空返回0,代表有0个字段;
  • 使用空格标志区分字段:上一个字符为空格,当前字符不为空格,字符段计数加一。

Language:cpp

class Solution {
public:
    //去掉字符串两端的空格
    string& trim(string &s) {
        if (s.empty()) {
            return s;
        }
        s.erase(0, s.find_first_not_of(" "));
        s.erase(s.find_last_not_of(" ") + 1);
        return s;
    }

    int countSegments(string s) {
        //字符串为空,返回0
        if (trim(s).empty()) {
            return 0;
        }
        int ans = 1;
        s = trim(s);   
        for (int i = 0; i < s.length(); i++) {
            //当上一个字符是空格,当前字符不是空格时,则为一个字段
            if (s[i-1] == ' ' && s[i] != ' ') {
                ans++;
            }
        }
        return ans;
    }
};

你可能感兴趣的:(LeetCode,String,segments)