Java, count only the start of each new word


  • 1
    A

    We know that a word always begins after the white space. We can count segments by counting only the places where i-th character is not white space and (i-1)-th character is white space. Do not forget that the word may begin from the position 0.

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

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.