zoukankan      html  css  js  c++  java
  • LeetCode_434. Number of Segments in a String

    434. Number of Segments in a String

    Easy

    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
    package leetcode.easy;
    
    public class NumberOfSegmentsInAString {
    	public int countSegments1(String s) {
    		String trimmed = s.trim();
    		if (trimmed.equals("")) {
    			return 0;
    		}
    		return trimmed.split("\s+").length;
    	}
    
    	public int countSegments2(String s) {
    		int segmentCount = 0;
    
    		for (int i = 0; i < s.length(); i++) {
    			if ((i == 0 || s.charAt(i - 1) == ' ') && s.charAt(i) != ' ') {
    				segmentCount++;
    			}
    		}
    
    		return segmentCount;
    	}
    
    	@org.junit.Test
    	public void test() {
    		System.out.println(countSegments1("Hello, my name is John"));
    		System.out.println(countSegments2("Hello, my name is John"));
    	}
    }
    
  • 相关阅读:
    java 字符串截取
    字符编码Unicode-正则表达式验证
    APP数据加密解密
    ThreadLocal线程局部变量
    用Eclipse进行远程Debug代码
    JPA对应关系
    JPA名称规则
    dubbo环境搭建
    历史表更新数据
    api加密算法
  • 原文地址:https://www.cnblogs.com/denggelin/p/11940034.html
Copyright © 2011-2022 走看看