LeetCode 434. Number of Segments in a String

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 }

 

posted @ 2017-02-25 21:49  Black_Knight  阅读(217)  评论(0编辑  收藏  举报