File tree Expand file tree Collapse file tree
LeetCode/easy/1784. Check if Binary String Has at Most One Segment of Ones Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ # 1784. Check if Binary String Has at Most One Segment of Ones
2+
3+ [ 링크] ( https://leetcode.com/problems/check-if-binary-string-has-at-most-one-segment-of-ones/description/ )
4+
5+ | 난이도 |
6+ | :----: |
7+ | Easy |
8+
9+ ## 설계
10+
11+ ### 시간 복잡도
12+
13+ 문자열의 길이를 N이라 하자.
14+
15+ 순회하며 1이 나오는 구간의 수를 셀 경우 O(N)의 시간 복잡도를 사용한다.
16+
17+ ### 공간 복잡도
18+
19+ 순회에 O(1)의 공간 복잡도를 사용한다.
20+
21+ ### 순회
22+
23+ | 내 코드 (ms) | 시간 복잡도 | 공간 복잡도 |
24+ | :----------: | :---------: | :---------: |
25+ | 0 | O(N) | O(1) |
26+
27+ ``` cpp
28+ bool checkOnesSegment (string s) {
29+ int size = s.size();
30+ int count = 0;
31+
32+ char before = '0';
33+ for (int i = 0; i < size; i++) {
34+ if (s[ i] == '0' && before == '1') {
35+ count++;
36+
37+ if (count > 1) return false;
38+ }
39+ before = s[i];
40+ }
41+ if (before == '1') count++;
42+
43+ return count <= 1;
44+ }
45+ ```
46+
47+ ## 고생한 점
Original file line number Diff line number Diff line change 1+ #include < algorithm>
2+ #include < climits>
3+ #include < cmath>
4+ #include < cstring>
5+ #include < functional>
6+ #include < iostream>
7+ #include < map>
8+ #include < numeric>
9+ #include < queue>
10+ #include < set>
11+ #include < stack>
12+ #include < string>
13+ #include < unordered_map>
14+ #include < unordered_set>
15+ #include < vector>
16+
17+ using namespace std ;
18+
19+ // one pass
20+ // time : O(N)
21+ // space : O(1)
22+ class Solution {
23+ public:
24+ bool checkOnesSegment (string s) {
25+ int size = s.size ();
26+ int count = 0 ;
27+
28+ char before = ' 0' ;
29+ for (int i = 0 ; i < size; i++) {
30+ if (s[i] == ' 0' && before == ' 1' ) {
31+ count++;
32+
33+ if (count > 1 ) return false ;
34+ }
35+ before = s[i];
36+ }
37+ if (before == ' 1' ) count++;
38+
39+ return count <= 1 ;
40+ }
41+ };
Original file line number Diff line number Diff line change 1+ Input: s = "1001"
2+ Output: false
3+
4+ ===
5+
6+ Input: s = "110"
7+ Output: true
You can’t perform that action at this time.
0 commit comments