[Solution]434. Number of Segments in a String

·

1 min read

Problem

Problem_Link

Solutions (time, space)

  1. using split()
  2. count word with condition

If the program need to limit the space, should use 2 way. But, normally using split seems better for developing speed.

using split() O(n), O(n)

class Solution {
    public int countSegments(String s) {
        //String trimmedS=s.trim();  //lower than java 11
        String trimmedS=s.strip(); //higher than java 11, it cover more kinds of space

        if(trimmedS.equals("")) return 0;

        String[] temp = trimmedS.split("\\p{Z}+"); //regex: all possible space+

        return temp.length;
    }
}

Explanation

  1. trim first and last space
  2. split by spaces
  3. count words

count word with condition O(n), O(1)

class Solution {
    public int countSegments(String s) {
        int counter = 0;

        for (int i = 0; i < s.length(); ++i) {
            if ((i == 0 || s.charAt(i - 1) == ' ') && s.charAt(i) != ' ') {
                ++counter;
            }
        }

        return counter;
    }
}

Explanation

loop each Characters with counting word.

word counting condition is

  1. if current position is not space and previous position is space (s.charAt(i - 1) == ' ') && s.charAt(i) != ' ')
  2. if current position is not space and previous position is null (for first word) (i == 0 && s.charAt(i) != ' ')