-
[LeetCode] 1869. Longer Contiguous Segments of Ones than ZerosLeetCode 2021. 10. 15. 16:33728x90
https://leetcode.com/problems/longer-contiguous-segments-of-ones-than-zeros/
Longer Contiguous Segments of Ones than Zeros - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
Longer Contiguous Segments of Ones than Zeros


1과 0으로 이루어진 스트링내에서
연속된 1의 길이가 긴지, 0의 길이가 긴지 판별하는 문제다.
현재 1과 0의 길이를 저장할 int를 각각 a,b
1과 0의 최대길이를 저장할 int를 각각 c,d라고 하자.
모두 0으로 초기화를 해준다음
문자열을 하나씩 훑어주자.
현재 문자열이 1일 경우,
현재 0의 길이를 초기화 시켜주는데, 그전에 최대 0의 길이를 max(d,b)로 저장해준다.
그 후 b = 0으로 초기화시켜주고 a는 ++ 해준다.
반대도 마찬가지로 해준다.
마지막으로 max(a,c)가 max(d,b)보다 큰지 체크해준다.
(마지막에도 max를 해주는 이유는 최종적인 길이를 최대길이와 비교해주지 않았으므로 체크해줘야한다.)
아래는 전체 풀이코드다.
class Solution { public: bool checkZeroOnes(string s) { int a=0,b=0,c=0,d=0; for (int i=0; i<s.size(); i++) { if (s[i]=='1') { d=max(d,b); b=0; a++; } else { c=max(c,a); a=0; b++; } } return max(a,c)>max(b,d); } };'LeetCode' 카테고리의 다른 글
[LeetCode] 122. Best Time to Buy and Sell Stock II (0) 2021.10.16 [LeetCode] 121. Best Time to Buy and Sell Stock (0) 2021.10.16 [LeetCode] 1961. Check If String Is a Prefix of Array (0) 2021.10.15 [LeetCode] 309. Best Time to Buy and Sell Stock with Cooldown (0) 2021.10.15 [LeetCode] 917. Reverse Only Letters (0) 2021.10.15