📌  相关文章
📜  删除一个字符后,最长的1的子字符串

📅  最后修改于: 2021-05-04 19:10:10             🧑  作者: Mango

给定长度为N的二进制字符串S ,任务是查找从字符串删除一个字符后,仅在字符串存在的由‘1’组成的最长子字符串。

例子:

方法1:想法是遍历字符串并在给定的字符串搜索‘0’ 。对于发现为‘0’的每个字符,请添加其相邻子字符串‘1’的长度。打印获得的所有此类长度的最大值。

下面是上述方法的实现:

C++
// C++ Program to implement
// the above approach
#include 
using namespace std;
 
// Function to calculate the length of the
// longest substring of '1's that can be
// obtained by deleting one character
int longestSubarray(string s)
{
    // Add '0' at the end
    s += '0';
 
    // Iterator to traverse the string
    int i;
 
    // Stores maximum length
    // of required substring
    int res = 0;
 
    // Stores length of substring of '1'
    // preceding the current character
    int prev_one = 0;
 
    // Stores length of substring of '1'
    // succeeding the current character
    int curr_one = 0;
 
    // Counts number of '0's
    int numberOfZeros = 0;
 
    // Traverse the string S
    for (i = 0; i < s.length(); i++) {
 
        // If current character is '1'
        if (s[i] == '1') {
 
            // Increase curr_one by one
            curr_one += 1;
        }
 
        // Otherwise
        else {
 
            // Increment numberofZeros by one
            numberOfZeros += 1;
 
            // Count length of substring
            // obtained y concatenating
            // preceding and succeeding substrings of '1'
            prev_one += curr_one;
 
            // Store maximum size in res
            res = max(res, prev_one);
 
            // Assign curr_one to prev_one
            prev_one = curr_one;
 
            // Reset curr_one
            curr_one = 0;
        }
    }
 
    // If string contains only one '0'
    if (numberOfZeros == 1) {
        res -= 1;
    }
 
    // Return the answer
    return res;
}
 
// Driver Code
int main()
{
    string S = "1101";
    cout << longestSubarray(S);
    return 0;
}


Java
// Java program to implement
// the above approach
import java.util.Arrays;
  
class GFG{
      
// Function to calculate the length of the
// longest substring of '1's that can be
// obtained by deleting one character
static int longestSubarray(String s)
{
     
    // Add '0' at the end
    s += '0';
     
    // Iterator to traverse the string
    int i;
     
    // Stores maximum length
    // of required substring
    int res = 0;
     
    // Stores length of substring of '1'
    // preceding the current character
    int prev_one = 0;
  
    // Stores length of substring of '1'
    // succeeding the current character
    int curr_one = 0;
  
    // Counts number of '0's
    int numberOfZeros = 0;
  
    // Traverse the string S
    for(i = 0; i < s.length(); i++)
    {
         
        // If current character is '1'
        if (s.charAt(i) == '1')
        {
             
            // Increase curr_one by one
            curr_one += 1;
        }
  
        // Otherwise
        else
        {
             
            // Increment numberofZeros by one
            numberOfZeros += 1;
  
            // Count length of substring
            // obtained y concatenating
            // preceding and succeeding
            // substrings of '1'
            prev_one += curr_one;
  
            // Store maximum size in res
            res = Math.max(res, prev_one);
  
            // Assign curr_one to prev_one
            prev_one = curr_one;
  
            // Reset curr_one
            curr_one = 0;
        }
    }
  
    // If string contains only one '0'
    if (numberOfZeros == 1)
    {
        res -= 1;
    }
     
    // Return the answer
    return res;
}
  
// Driver Code
public static void main (String[] args)
{
    String S = "1101";
     
    System.out.println(longestSubarray(S));
}
}
 
// This code is contributed by code_hunt


Python3
# Python3 program to implement
# the above approach
 
# Function to calculate the length of the
# longest substring of '1's that can be
# obtained by deleting one character
def longestSubarray(s):
     
    # Add '0' at the end
    s += '0'
 
    # Iterator to traverse the string
    i = 0
 
    # Stores maximum length
    # of required substring
    res = 0
 
    # Stores length of substring of '1'
    # preceding the current character
    prev_one = 0
 
    # Stores length of substring of '1'
    # succeeding the current character
    curr_one = 0
 
    # Counts number of '0's
    numberOfZeros = 0
 
    # Traverse the string S
    for i in range(len(s)):
         
        # If current character is '1'
        if (s[i] == '1'):
             
            # Increase curr_one by one
            curr_one += 1
 
        # Otherwise
        else:
             
            # Increment numberofZeros by one
            numberOfZeros += 1
 
            # Count length of substring
            # obtained y concatenating
            # preceding and succeeding
            # substrings of '1'
            prev_one += curr_one
 
            # Store maximum size in res
            res = max(res, prev_one)
 
            # Assign curr_one to prev_one
            prev_one = curr_one
 
            # Reset curr_one
            curr_one = 0
 
    # If string contains only one '0'
    if (numberOfZeros == 1):
        res -= 1
 
    # Return the answer
    return res
 
# Driver Code
if __name__ == '__main__':
     
    S = "1101"
     
    print(longestSubarray(S))
 
# This code is contributed by ipg2016107


C#
// C# program to implement
// the above approach
using System;
class GFG
{
      
// Function to calculate the length of the
// longest substring of '1's that can be
// obtained by deleting one character
static int longestSubarray(String s)
{
     
    // Add '0' at the end
    s += '0';
     
    // Iterator to traverse the string
    int i;
     
    // Stores maximum length
    // of required substring
    int res = 0;
     
    // Stores length of substring of '1'
    // preceding the current character
    int prev_one = 0;
  
    // Stores length of substring of '1'
    // succeeding the current character
    int curr_one = 0;
  
    // Counts number of '0's
    int numberOfZeros = 0;
  
    // Traverse the string S
    for(i = 0; i < s.Length; i++)
    {
         
        // If current character is '1'
        if (s[i] == '1')
        {
             
            // Increase curr_one by one
            curr_one += 1;
        }
  
        // Otherwise
        else
        {
             
            // Increment numberofZeros by one
            numberOfZeros += 1;
  
            // Count length of substring
            // obtained y concatenating
            // preceding and succeeding
            // substrings of '1'
            prev_one += curr_one;
  
            // Store maximum size in res
            res = Math.Max(res, prev_one);
  
            // Assign curr_one to prev_one
            prev_one = curr_one;
  
            // Reset curr_one
            curr_one = 0;
        }
    }
  
    // If string contains only one '0'
    if (numberOfZeros == 1)
    {
        res -= 1;
    }
     
    // Return the answer
    return res;
}
  
// Driver Code
public static void Main(String[] args)
{
    String S = "1101";
     
    Console.WriteLine(longestSubarray(S));
}
}
 
 
// This code is contributed by shikhasingrajput


C++
// C++ Program to implement
// the above approach
#include 
using namespace std;
 
// Function to calculate the length of the
// longest substring of '1's that can be
// obtained by deleting one character
int longestSubarray(string s)
{
    // Initializing i and j as left and
    // right boundaries of sliding window
    int i = 0, j = 0, k = 1;
 
    for (j = 0; j < s.size(); ++j) {
 
        // If current character is '0'
        if (s[j] == '0')
 
            // Decrement k by one
            k--;
 
        // If k is less than zero and character
        // at ith index is '0'
        if (k < 0 && s[i++] == '0')
            k++;
    }
 
    // Return result
    return j - i - 1;
}
 
// Driver Code
int main()
{
    string S = "011101101";
    cout << longestSubarray(S);
 
    return 0;
}


Java
// Java Program to implement
// the above approach
 
import java.util.*;
 
class GFG{
 
// Function to calculate the length of the
// longest subString of '1's that can be
// obtained by deleting one character
static int longestSubarray(String s)
{
    // Initializing i and j as left and
    // right boundaries of sliding window
    int i = 0, j = 0, k = 1;
 
    for (j = 0; j < s.length(); ++j)
    {
 
        // If current character is '0'
        if (s.charAt(j) == '0')
 
            // Decrement k by one
            k--;
 
        // If k is less than zero and character
        // at ith index is '0'
        if (k < 0 && s.charAt(i++) == '0')
            k++;
    }
 
    // Return result
    return j - i - 1;
}
 
// Driver Code
public static void main(String[] args)
{
    String S = "011101101";
    System.out.print(longestSubarray(S));
 
}
}
 
// This code contributed by gauravrajput1


Python3
# Python3 program to implement
# the above approach
 
# Function to calculate the length of the
# longest substring of '1's that can be
# obtained by deleting one character
def longestSubarray(s):
     
    # Initializing i and j as left and
    # right boundaries of sliding window
    i = 0
    j = 0
    k = 1
 
    for j in range(len(s)):
         
        # If current character is '0'
        if (s[j] == '0'):
 
            # Decrement k by one
            k -= 1
 
        # If k is less than zero and character
        # at ith index is '0'
        if (k < 0 ):
            if s[i] == '0':
                k += 1
                 
            i += 1
             
    j += 1
 
    # Return result
    return j - i - 1
 
# Driver Code
if __name__ == "__main__" :
 
    S = "011101101"
     
    print(longestSubarray(S))
 
# This code is contributed by AnkThon


C#
// C# program to implement
// the above approach
using System;
 
class GFG{
 
// Function to calculate the length of the
// longest subString of '1's that can be
// obtained by deleting one character
static int longestSubarray(string s)
{
     
    // Initializing i and j as left and
    // right boundaries of sliding window
    int i = 0, j = 0, k = 1;
 
    for(j = 0; j < s.Length; ++j)
    {
         
        // If current character is '0'
        if (s[j] == '0')
         
            // Decrement k by one
            k -= 1;
 
        // If k is less than zero and character
        // at ith index is '0'
        if (k < 0 && s[i++] == '0')
            k++;
    }
 
    // Return result
    return j - i - 1;
}
 
// Driver Code
public static void Main(string[] args)
{
    string S = "011101101";
     
    Console.Write(longestSubarray(S));
}
}
 
// This code is contributed by AnkThon


输出:
3

时间复杂度: O(N)
辅助空间: O(N)

方法2:解决此问题的另一种方法是使用滑动窗口技术在删除单个字符后查找仅包含“ 1”的子字符串的最大长度。请按照以下步骤解决问题:

  • 0初始化3个整数变量i,j ,用1初始化k
  • 遍历字符串S的字符。
    • 对于每个被遍历的字符,请检查其是否为“ 0” 。如果确定为真,则将k1
    • 如果k <0且字符在i索引是“0”,增量ki增加1
    • j递增1
  • 最后,在完全遍历字符串之后,打印长度j – i – 1

下面是上述方法的实现:

C++

// C++ Program to implement
// the above approach
#include 
using namespace std;
 
// Function to calculate the length of the
// longest substring of '1's that can be
// obtained by deleting one character
int longestSubarray(string s)
{
    // Initializing i and j as left and
    // right boundaries of sliding window
    int i = 0, j = 0, k = 1;
 
    for (j = 0; j < s.size(); ++j) {
 
        // If current character is '0'
        if (s[j] == '0')
 
            // Decrement k by one
            k--;
 
        // If k is less than zero and character
        // at ith index is '0'
        if (k < 0 && s[i++] == '0')
            k++;
    }
 
    // Return result
    return j - i - 1;
}
 
// Driver Code
int main()
{
    string S = "011101101";
    cout << longestSubarray(S);
 
    return 0;
}

Java

// Java Program to implement
// the above approach
 
import java.util.*;
 
class GFG{
 
// Function to calculate the length of the
// longest subString of '1's that can be
// obtained by deleting one character
static int longestSubarray(String s)
{
    // Initializing i and j as left and
    // right boundaries of sliding window
    int i = 0, j = 0, k = 1;
 
    for (j = 0; j < s.length(); ++j)
    {
 
        // If current character is '0'
        if (s.charAt(j) == '0')
 
            // Decrement k by one
            k--;
 
        // If k is less than zero and character
        // at ith index is '0'
        if (k < 0 && s.charAt(i++) == '0')
            k++;
    }
 
    // Return result
    return j - i - 1;
}
 
// Driver Code
public static void main(String[] args)
{
    String S = "011101101";
    System.out.print(longestSubarray(S));
 
}
}
 
// This code contributed by gauravrajput1

Python3

# Python3 program to implement
# the above approach
 
# Function to calculate the length of the
# longest substring of '1's that can be
# obtained by deleting one character
def longestSubarray(s):
     
    # Initializing i and j as left and
    # right boundaries of sliding window
    i = 0
    j = 0
    k = 1
 
    for j in range(len(s)):
         
        # If current character is '0'
        if (s[j] == '0'):
 
            # Decrement k by one
            k -= 1
 
        # If k is less than zero and character
        # at ith index is '0'
        if (k < 0 ):
            if s[i] == '0':
                k += 1
                 
            i += 1
             
    j += 1
 
    # Return result
    return j - i - 1
 
# Driver Code
if __name__ == "__main__" :
 
    S = "011101101"
     
    print(longestSubarray(S))
 
# This code is contributed by AnkThon

C#

// C# program to implement
// the above approach
using System;
 
class GFG{
 
// Function to calculate the length of the
// longest subString of '1's that can be
// obtained by deleting one character
static int longestSubarray(string s)
{
     
    // Initializing i and j as left and
    // right boundaries of sliding window
    int i = 0, j = 0, k = 1;
 
    for(j = 0; j < s.Length; ++j)
    {
         
        // If current character is '0'
        if (s[j] == '0')
         
            // Decrement k by one
            k -= 1;
 
        // If k is less than zero and character
        // at ith index is '0'
        if (k < 0 && s[i++] == '0')
            k++;
    }
 
    // Return result
    return j - i - 1;
}
 
// Driver Code
public static void Main(string[] args)
{
    string S = "011101101";
     
    Console.Write(longestSubarray(S));
}
}
 
// This code is contributed by AnkThon
输出:
5

时间复杂度: O(N)
辅助空间: O(N)