Max Consecutive Ones-LeetCode#485

485. Max Consecutive Ones
Given a binary array, find the maximum number of consecutive 1s in this array.
Example 1:

Input: [1,1,0,1,1,1]
Output: 3
Explanation: The first two digits or the last three digits are consecutive 1s.
    The maximum number of consecutive 1s is 3.

Note:

  • The input array will only contain 0 and 1.
  • The length of input array is a positive integer and will not exceed 10,000

思路:查找二进制数组中1的连续最长长度。利用String的indexOf计算0出现的位置,截取长度为1的连续长度。
代码如下:

/**
 * @Author: Poldi
 * @Date: 2019-06-01 17:34
 * @Description: 485. Max Consecutive Ones
 */
public class MaxConsecutiveOnes {
    public static int findMaxConsecutiveOnes(int[] nums) {
        StringBuilder stringBuilder = new StringBuilder();
        for (int a : nums) {
            stringBuilder.append(a);
        }
        int temp = sliceStr(stringBuilder.toString(), 0);
        return temp;
    }
    public static int sliceStr(String str, int temp) {
        if (str.equals("")) return temp;
        if (!str.contains("0")) {
            return temp > str.length() ? temp : str.length();
        }
        if (str.indexOf("0") > temp) {
            temp = str.indexOf("0");
        }
        str = str.substring(str.indexOf("0") + 1);
        return sliceStr(str, temp);
    }
    public static void main(String[] args) {
        int[] nums = {1, 1, 0, 1, 1, 1, 0, 1, 1};
        MaxConsecutiveOnes.findMaxConsecutiveOnes(nums);
    }
}

ps:好久没做算法了….懒啊

文章已创建 112

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

相关文章

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部