본문 바로가기
츄Log/알고리즘 연습장

연습#13

by 츄츄🦭 2023. 12. 12.
728x90

 

바로 이어서 한 문제 더 풀었습니다.

2609. Find the Longest Balanced Substring of a Binary String

 

두 가지의 접근법이 있는데요,

하나는 "01"이라는 규칙을 이용해서 푸는 것과,

하나는 문자열을 순회하면서 계산하는 방법입니다.

class Solution {
    public int findTheLongestBalancedSubstring(String s) {
        int res = 0;
        String temp = "01";
        while(temp.length() <= s.length()){
            if(s.contains(temp))
                res = temp.length();
            temp = "0" + temp + "1";
        }
        return res;
    }
}

class Solution {
    public int findTheLongestBalancedSubstring(String s) {
        int zeroCount = 0;
        int oneCount = 0;
        int totalMax = Integer.MIN_VALUE;
        int i = 0;
        while (i < s.length()) {
            while (i < s.length() && s.charAt(i) == '0') {
                zeroCount++;
                i++;
            }
            while (i < s.length() && s.charAt(i) == '1') {
                oneCount++;
                i++;
            }
            totalMax = Math.max(totalMax, 2 *  Math.min(zeroCount, oneCount));
            zeroCount = 0;
            oneCount = 0;
        }
        return totalMax;
    }
}

 

어렵다ㅠㅠ 알고리즘.. 어렵습니다 흑흑

 

728x90

'츄Log > 알고리즘 연습장' 카테고리의 다른 글

연습#15  (0) 2023.12.14
연습#14  (0) 2023.12.13
연습#12  (0) 2023.12.12
연습#11 Check if the sentence Is Pangram  (1) 2023.12.11
연습#10 Consecutive Characters  (0) 2023.12.10