Java one scan solution


  • 0
    D
    public class Solution {
        public int countSegments(String s) {
            if (s == null || s.length() == 0) {
                return 0;
            }
            int space = 0;
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < s.length(); i++) {
                char ch = s.charAt(i);
                if (ch != ' ' || (sb.length() > 0 && sb.charAt(sb.length() - 1) != ' ')) {
                    sb.append(ch);
                    space += ch == ' ' ? 1 : 0;
                }
            }
            return sb.length() == 0 ? 0 : (sb.charAt(sb.length() - 1) == ' ' ? space : space + 1);
        }
    }
    

Log in to reply
 

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