[LeetCode] Maximum Score After Splitting a String

아르당·5일 전

LeetCode

목록 보기
298/303
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

0과 1로 된 문자열 s가 주어졌을 때, 문자열을 두 개의 비어있지 않은 부분 문자열(즉, 왼쪽 부분 문자열과 오른쪽 부분 문자열)로 분할한 후 가장 높은 점수를 반환해라.

문자열을 나눈 후 점수는 왼쪽 부분 문자열에서 0의 개수와 오른쪽 부분 문자열에서 1의 개수를 더한 값이다.

Example

#1
Input: s = "011101"
Output: 5
Explanation:
두 개의 비어있지 않는 문자열 s를 나눈 모든 방법이다.
left = "0", right = "11101", score = 1 + 4 = 5
left = "01", right = "1101", score = 1 + 3 = 4
left = "011", right = "101", score = 1 + 2 = 3
left = "0111", right = "01", score = 1 + 1 = 2
left = "01110", right = "1", score = 2 + 1 = 3

#2
Input: s = "00111"
Output: 5
Explanation: left = "00"이고 right = "111"이면 최대 점수 2 + 3 = 5를 얻는다.

#3
Input: s = "1111"
Output: 3

Constraints

  • 2 <= s.length <= 500
  • 문자열 s는 '0'과 '1'의 문자로 구성된다.

Solved

class Solution {
    public int maxScore(String s) {
        int oneTotal = 0;

        for(char c : s.toCharArray()){
            if(c == '1'){
                oneTotal++;
            }
        }

        int zeroCount = 0;
        int oneCount = 0;
        int score = Integer.MIN_VALUE;

        for(int i = 0; i < s.length() - 1; i++){
            if(s.charAt(i) == '0'){
                zeroCount++;
            }else{
                oneCount++;
            }

            int cur = zeroCount + (oneTotal - oneCount);
            score = Math.max(score, cur);
        }

        return score;
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글