本文主要是介绍Number of Segments in a String,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目地址:https://leetcode.com/problems/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
题目的意思就是让我们看看输入的字符串里面有多少个分割,基本上就用空格分割。
题目的例子已经给的很明确,也是最理想的状态,里面有五个单词(分割),所以输出5。
如果前后加了空格呢?例如:
" Hello, my name is John"
"Hello, my name is John "
" Hello, my name is John "
当然这种情况也应该输出5。
再如果是这样的情况呢?字符串中间插有多个连续的空格,例如
"Hello, my name is John"
这种情况同样应该输出5。
再比如,假如里面有其他字符呢(题目中已经说了,不会有不可见字符),比如:
"Hello, my \" name \" is John"
好了,我想到情况差不多了,那么思路也比较明确了,实现代码如下:
public class NumberOfSegmentsInAString {public int countSegments(String s) {//去除两边的空格s = s.trim();if (s.length() == 0)return 0;if (s.length() == 1) {if (s == " ")return 0;return 1;}//去除连续的空格,只保留一个for (int i = 0; i < s.length() - 1; i++) {if (s.charAt(i) == ' ' && s.charAt(i + 1) == ' ') {s = s.substring(0, i) + s.substring(i + 1);i--;}}return s.split(" ").length;}public static void main(String[] args) {NumberOfSegmentsInAString numberOfSegmentsInAString = new NumberOfSegmentsInAString();System.out.println(numberOfSegmentsInAString.countSegments(" Hello, my d name is John "));}
}
这篇关于Number of Segments in a String的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!