牛客网 2018校招真题 网易 交错01串

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_32767041/article/details/86489637

Description

牛客网 2018校招真题 交错01串

Solving Ideas

动态规划:

State:
dp[i]: 以s[i]为结尾的交错01串的最大长度

Initial State:
dp[0] = 1

State Transition:
dp[i] = (s[i - 1] != s[i]) ? dp[i - 1] + 1 : 1; (i >= 1)

Time complexity : O(n)
Space complexity : O(n)

Solution

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @author wylu
 */
public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        char[] s = br.readLine().toCharArray();
        //以s[i]为结尾的交错01串的最大长度
        int[] dp = new int[s.length];
        dp[0] = 1;
        int res = dp[0];
        for (int i = 1; i < s.length; i++) {
            dp[i] = (s[i - 1] != s[i]) ? dp[i - 1] + 1 : 1;
            res = Math.max(res, dp[i]);
        }
        System.out.println(res);
    }
}

优化,将空间复杂度降到 O ( 1 ) O(1)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @author wylu
 */
public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        char[] s = br.readLine().toCharArray();
        int res = 1, count = 1;
        for (int i = 1; i < s.length; i++) {
            if (s[i - 1] != s[i]) {
                count++;
                res = Math.max(res, count);
            } else {
                count = 1;
            }
        }
        System.out.println(res);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_32767041/article/details/86489637
今日推荐