给出一个显示字符串大小的整数N,在下一行给出一个字符串 它包含一个只有0和1的字符串 。任务是每次删除两个零字符之间的单个字符。 在每个回合中,只会从字符串中删除满足以下条件的一个字符:
null
- 它的两边都必须被零包围。
例如:
Input : str = "1001Output : str = "1001"Input : str = "10101Output : str = "1001"
使用一个从1到N–1的循环,检查是否有任何元素位于两个零之间,使得s[i–1]=“0”和s[i+1]=“0”。如果条件满足,则删除该位置的字符,然后再次开始搜索模式。
C++
// C++ program to delete elements between zeros #include <bits/stdc++.h> using namespace std; // Function to find the string // after operation string findstring(string s) { int n = s.length(); // Traversing through string for ( int i = 1; i < n - 1; i++) { // Checking for character // Between two zeros if ((s.at(i - 1) == '0' && s.at(i + 1) == '0' )) { // deleting the character // At specific position s.erase(i, 1); i--; if (i > 0 && s.at(i - 1) == '0' ) i--; // updating the length // of the string n = s.length(); } } return s; } // Drivers code int main() { cout << findstring( "100100" ); return 0; } |
JAVA
// Java program to delete elements between zeros import java.util.*; public class GFG { // Function to find the string // after operation static String findstring(String s) { int n = s.length(); // use for loop to remove the // character between two zeros for ( int i = 1 ; i < n - 1 ; i++) { // Checking for character // Between two zeros if ((s.charAt(i - 1 ) == '0' && s.charAt(i + 1 ) == '0' )) { // deleting the character // At specific position s = s.substring( 0 , i) + s.substring(i + 1 ); i--; if (i > 0 && s.charAt(i - 1 ) == '0' ) i--; // updating the length // of the string n = s.length(); } } return s; } // Driver code public static void main(String[] args) { String s= "100100" ; System.out.println(findstring(s)); } } |
Python3
# Python3 program to delete elements # between zeros # Function to find the string # after operation def findstring(s): n = len (s) s = list (s) i = 1 # Traversing through string while i < n - 1 : # Checking for character # Between two zeros if (s[i - 1 ] = = '0' and s[i + 1 ] = = '0' ): # Deleting the character # At specific position s.pop(i) i - = 1 if i > 0 and s[i - 1 ] = = '0' : i - = 1 # Updating the length # of the string n = len (s) i + = 1 return ''.join(s) # Driver code if __name__ = = '__main__' : print (findstring( '100100' )) # This code is contributed by rutvik_56 |
C#
// C# program to delete // elements between zeros using System; class GFG { // Function to find the // string after operation static string findstring( string s) { int n = s.Length; string st = "" ; // Traversing through string for ( int i = 1; i < n - 1; i++) { // Checking for character // Between two zeros if ((s[i - 1] == '0' && s[i + 1] == '0' )) { // deleting the character // At specific position st = s.Remove(i, 1); s = st; i--; if (i > 0 && s[i - 1] == '0' ) i--; // updating the length // of the string n = s.Length; } } return s; } // Driver code static void Main() { Console.Write(findstring( "100100" )); } } // This code is contributed by // Manish Shaw(manishshaw1) |
输出:
100
时间复杂性: O(N),其中N是输入字符串的大小。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END