【Lintcode】1243. Number of Segments in a String
阿新 • • 發佈:2020-12-19
技術標籤:# 棧、佇列、串及其他資料結構字串leetcode演算法
題目地址:
https://www.lintcode.com/problem/number-of-segments-in-a-string/description
給定一個字串 s s s,問其按照連續空格進行切割能切出多少個不同的非空的部分。
遇到非空格時就擷取。程式碼如下:
public class Solution {
/**
* @param s: a string
* @return: the number of segments in a string
*/
public int countSegments(String s) {
// write yout code here
int res = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == ' ') {
continue;
}
int j = i;
while (j < s.length() && s.charAt(j) != ' ') {
j++;
}
res++;
i = j - 1;
}
return res;
}
}
時間複雜度 O ( l s ) O(l_s) O(ls),空間 O ( 1 ) O(1) O(1)。