【Leetcode】434. Number of Segments in a String

    xiaoxiao2021-03-25  157

    思路:

    遍历整个字符串,用flag标记是否已经遇到了第一个空格,避免连续几个空格时,多次计算。若遇到空格且flag为0,则计数,并置flag为1,表示已经遇到了第一个空格,若遇到的不是空格,则置flag为0。

    public class Solution { public int countSegments(String s) { s = s.trim(); if (s.equals("")) return 0; int result = 0, flag = 0; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == ' ' && flag == 0) { result++; flag = 1; } if (s.charAt(i) != ' ') flag = 0; } return result + 1; } }

    Runtime:3ms

    转载请注明原文地址: https://ju.6miu.com/read-8673.html

    最新回复(0)