FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
leetcode/java/434_Number_of_Segments_in_a_String.java at master · jakehoare/leetcode · GitHub
jakehoare
/
leetcode
Public
Notifications
You must be signed in to change notification settings
Fork
30
Star
51
Code
Issues
0
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
leetcode
/
java
/
434_Number_of_Segments_in_a_String.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
30 lines (24 loc) · 916 Bytes
Breadcrumbs
leetcode
/
java
/
434_Number_of_Segments_in_a_String.java
Copy path
File metadata and controls
30 lines (24 loc) · 916 Bytes
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/*
https://leetcode.com/problems/number-of-segments-in-a-string/
Count the number of segments in a string, where a segment is defined to be a contiguous sequence of
non-space characters. Note that the string does not contain any non-printable characters.
Iterate over characters. Boolean blank indicates if previous char was whitespace. If blank and char is not whitespace
we have a new segment and blank is false. If whitespace, blank is true.
Time - O(n)
Space - O(1)
*/
public
class
Solution
{
public
int
countSegments
(
String
s
) {
int
segments
=
0
;
boolean
blank
=
true
;
for
(
int
i
=
0
;
i
<
s
.
length
(); ++
i
) {
if
(
blank
&& !
Character
.
isWhitespace
(
s
.
charAt
(
i
))) {
++
segments
;
blank
=
false
;
}
else
if
(
Character
.
isWhitespace
(
s
.
charAt
(
i
)))
blank
=
true
;
}
return
segments
;
}
}
Back
|
FazBrowse Home
|
New Git URL