434. Number of Segments in a Str

2016-12-06  本文已影响26人  hyhchaos

Java

public class Solution {
    public int countSegments(String s) {
        if(s.equals("")) return 0;
        int count=0;
        for(int i=0;i<s.length()-1;i++)
        {
            if(s.charAt(i)!=' '&&s.charAt(i+1)==' ')
            count++;
        }
        if(s.charAt(s.length()-1)!=' ') count++;
        return count;
    }
}

Javascript,利用split

/**
 * @param {string} s
 * @return {number}
 */
var countSegments = function(s) {
    if(s==="") return 0;
    var count=0;
    var m=s.split(" ");
    for(var i=0;i<m.length;i++)
    {
        console.log(m[i]);
        if(m[i]!=="")
        count++;
    }
    return count;
};

优解,Java,有想法

 public int countSegments(String s) {
    return ("x " + s).split(" +").length - 1;
}
上一篇下一篇

猜你喜欢

热点阅读