首页 > 其他 > 详细

Number of Segments in a String Leetcode

时间:2017-01-19 07:54:17      阅读:331      评论:0      收藏:0      [点我收藏+]

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

 

这道题用了split什么的都过不了,后来还是用指针解决了,所以还是手撕代码比较有效?但是最近老是喜欢用双指针,代码不够优雅。。。

public class Solution {
    public int countSegments(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        int pre = 0, cur = 0, sum = 0;
        for (int i = 0; i < s.length(); i++) {
            if (pre == 0 && cur == 0 && s.charAt(cur) != ‘ ‘) {
                sum++;
            }
            if (s.charAt(pre) == ‘ ‘ && s.charAt(cur) != ‘ ‘) {
                sum++;
            }
            pre = cur;
            cur++;
        }
        return sum;
        
    }
}

不用指针,优雅多了。。。

public class Solution {
    public int countSegments(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        int sum = 0;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) != ‘ ‘ && (i == 0 || s.charAt(i - 1) == ‘ ‘)) {
                sum++;
            }
        }
        return sum;
        
    }
}

 

Number of Segments in a String Leetcode

原文:http://www.cnblogs.com/aprilyang/p/6305344.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!