LeetCode_434. Number of Segments in a String

时间:2024-09-03 10:35:50

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"));
}
}