LeetCode 434. Number of Segments in a String

本文介绍了一种简单的方法来计算字符串中非空格字符组成的连续序列的数量。通过使用Java中的trim()和split()方法,可以有效地解决这个问题。

434. Number of Segments in a String

Description Submission Solutions

  • Total Accepted: 13229
  • Total Submissions: 35604
  • Difficulty: Easy
  • Contributors: love_FDU_llp

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

Subscribe to see which companies asked this question.


【题目分析】

求一个字符串不包含空字符的子串有多少个。


【思路】

1. 使用Srtring.spilt方法。split方法需要特别注意的一点是,如果字符串的头部与split传入的字符串正好匹配,那么结果会多返回一个空字符串。而在尾部出现则不会出现这种情况。


【java代码】

1 public class Solution {
2     public int countSegments(String s) {
3         if(s == null) return 0;
4         s = s.trim();
5         if(s.length() == 0) return 0;
6         
7         return s.split("\\s+").length;
8     }
9 }

 

转载于:https://www.cnblogs.com/liujinhong/p/6442965.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值