LintCode-简单 1243.字符串中的单词数

1243. 字符串中的单词数

计算字符串中的单词数,其中一个单词定义为不含空格的连续字符串。

样例

Example:

Input: "Hello, my name is John"
Output: 5
Explanation:There are five string "Hello"、"my"、"name"、"is"、"John"

注意事项

字符串中不包含任何 无法打印 的字符.

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

猜你喜欢

转载自blog.csdn.net/weixin_44977914/article/details/89972323
今日推荐