zoukankan      html  css  js  c++  java
  • 434. 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.

    Please note that the string does not contain any non-printable characters.

    Example:

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

    链接:https://leetcode.com/problems/number-of-segments-in-a-string/#/description

    3/25/2017

     1 public class Solution {
     2     public int countSegments(String s) {
     3         boolean inSegment = false;
     4         int count = 0;
     5         for (int i = 0; i < s.length(); i++) {
     6             if (s.charAt(i) == ' ') {
     7                 if (inSegment) inSegment = false;
     8             } else {
     9                 if (!inSegment) {
    10                     inSegment = true;
    11                     count++;
    12                 }
    13             }
    14         }
    15         return count;
    16     }
    17 }

    别人的精简版

    1 public int countSegments(String s) {
    2     int res=0;
    3     for(int i=0; i<s.length(); i++)
    4         if(s.charAt(i)!=' ' && (i==0 || s.charAt(i-1)==' '))
    5             res++;        
    6     return res;
    7 }
  • 相关阅读:
    L208
    L207
    L206
    L205 EE
    L204
    监控glusterfs
    监控elssticSearch健康状态
    防火墙
    创建逻辑卷
    编译安装nginx,并使用systemd管理nginx
  • 原文地址:https://www.cnblogs.com/panini/p/6619163.html
Copyright © 2011-2022 走看看