LeetCode //C - 434. Number of Segments in a String

434. Number of Segments in a String

Given a string s, return the number of segments in the string.

A segment is defined to be a contiguous sequence of non-space characters.
 

Example 1:

Input: s = “Hello, my name is John”
Output: 5
Explanation: The five segments are [“Hello,”, “my”, “name”, “is”, “John”]

Example 2:

Input: s = “Hello”
Output: 1

Constraints:
  • 0 <= s.length <= 300
  • s consists of lowercase and uppercase English letters, digits, or one of the following characters “!@#$%^&*()_±=',.:”.
  • The only space character in s is ’ '.

From: LeetCode
Link: 434. Number of Segments in a String


Solution:

Ideas:

1. Initialize Counters: count keeps track of segments, and inSegment indicates whether we’re inside a word.

2. Iterate Through Characters:

  • If the current character is not a space, check if we are at the start of a new segment (inSegment == 0). If so, increment count and set inSegment to 1.
  • If the current character is a space, set inSegment to 0, signaling the end of a segment.

3. Return count: After iterating through the string, count holds the total number of segments.

Code:
int countSegments(char *s) {
    
    
    int count = 0;
    int inSegment = 0;  // Tracks if we are within a segment

    for (int i = 0; s[i] != '\0'; i++) {
    
    
        if (s[i] != ' ') {
    
    
            if (!inSegment) {
    
      // Start of a new segment
                count++;
                inSegment = 1;
            }
        } else {
    
    
            inSegment = 0;  // End of a segment
        }
    }

    return count;
}

猜你喜欢

转载自blog.csdn.net/navicheung/article/details/143354627