给定一个字符串str,任务是提取存在于两个定界符之间的子字符串,即‘[‘和‘]’ 。
例子:
Input: str = “[This is a string to be extracted]”
Output: This is a string to be extracted
Explanation: The square brackets ‘[‘ and ‘]’ serve as delimiters in the given string.
Input: str= “[This is first] ignored text [This is second]”
Output:
This is first
This is second
Explanation: The square brackets ‘[‘ and ‘]’ serve as delimiters in the given string.
基于堆栈方法:遍历字符串的字符并插入的每一个索引“[”遇到堆中。对于遇到的每个“]” ,只需弹出存储在堆栈顶部的索引,然后打印介于两者之间的子字符串。
下面是上述方法的实现
C++
// C++ Program to implement
// the above approach
#include
using namespace std;
// Function to print strings present
// between any pair of delimeters
void printSubsInDelimeters(string str)
{
// Stores the indices of
stack dels;
for (int i = 0; i < str.size(); i++) {
// If opening delimeter
// is encountered
if (str[i] == '[') {
dels.push(i);
}
// If closing delimeter
// is encountered
else if (str[i] == ']' && !dels.empty()) {
// Extract the position
// of opening delimeter
int pos = dels.top();
dels.pop();
// Length of substring
int len = i - 1 - pos;
// Extract the substring
string ans = str.substr(
pos + 1, len);
cout << ans << endl;
}
}
}
// Driver Code
int main()
{
string str = "[This is first] ignored text [This is second]";
printSubsInDelimeters(str);
return 0;
}
Java
// Java program to implement
// the above approach
import java.util.*;
class GFG{
// Function to print Strings present
// between any pair of delimeters
static void printSubsInDelimeters(String str)
{
// Stores the indices of
Stack dels = new Stack();
for(int i = 0; i < str.length(); i++)
{
// If opening delimeter
// is encountered
if (str.charAt(i) == '[')
{
dels.add(i);
}
// If closing delimeter
// is encountered
else if (str.charAt(i) == ']' &&
!dels.isEmpty())
{
// Extract the position
// of opening delimeter
int pos = dels.peek();
dels.pop();
// Length of subString
int len = i - 1 - pos;
// Extract the subString
String ans = str.substring(
pos + 1, pos + 1 + len);
System.out.print(ans + "\n");
}
}
}
// Driver Code
public static void main(String[] args)
{
String str = "[This is first] ignored text [This is second]";
printSubsInDelimeters(str);
}
}
// This code is contributed by shikhasingrajput
Python3
# Python3 Program to implement
# the above approach
# Function to print strings present
# between any pair of delimeters
def printSubsInDelimeters(string) :
# Stores the indices
dels = [];
for i in range(len(string)):
# If opening delimeter
# is encountered
if (string[i] == '[') :
dels.append(i);
# If closing delimeter
# is encountered
elif (string[i] == ']' and len(dels) != 0) :
# Extract the position
# of opening delimeter
pos = dels[-1];
dels.pop();
# Length of substring
length = i - 1 - pos;
# Extract the substring
ans = string[pos + 1 : pos + 1 + length];
print(ans);
# Driver Code
if __name__ == "__main__" :
string = "[This is first] ignored text [This is second]";
printSubsInDelimeters(string);
# This code is contributed by AnkThon
C#
// C# program to implement
// the above approach
using System;
using System.Collections;
class GFG{
// Function to print strings present
// between any pair of delimeters
static void printSubsInDelimeters(string str)
{
// Stores the indices of
Stack dels = new Stack();
for(int i = 0; i < str.Length; i++)
{
// If opening delimeter
// is encountered
if (str[i] == '[')
{
dels.Push(i);
}
// If closing delimeter
// is encountered
else if (str[i] == ']' && dels.Count > 0)
{
// Extract the position
// of opening delimeter
int pos = (int)dels.Peek();
dels.Pop();
// Length of substring
int len = i - 1 - pos;
// Extract the substring
string ans = str.Substring(
pos + 1, len);
Console.WriteLine(ans);
}
}
}
// Driver Code
static void Main()
{
string str = "[This is first] ignored text [This is second]";
printSubsInDelimeters(str);
}
}
// This code is contributed by divyesh072019
C++
// C++ program to implement
// the above approach
#include
#include
using namespace std;
// Function to print Strings present
// between any pair of delimeters
void printSubsInDelimeters(string str)
{
// Regex to extract the string
// between two delimiters
const regex pattern("\\[(.*?)\\]");
for(sregex_iterator it = sregex_iterator(
str.begin(), str.end(), pattern);
it != sregex_iterator(); it++)
{
// flag type for determining the
// matching behavior here it is
// for matches on 'string' objects
smatch match;
match = *it;
cout << match.str(1) << endl;
}
return;
}
// Driver Code
int main()
{
// Input String
string str = "[This is first] ignored text [This is second]";
// Function Call
printSubsInDelimeters(str);
return 0;
}
// This code is contributed by yuvraj_chandra
Java
// Java program to implement
// the above approach
import java.util.regex.*;
class GFG{
// Function to print Strings present
// between any pair of delimeters
public static void printSubsInDelimeters(String str)
{
// Regex to extract the string
// between two delimiters
String regex = "\\[(.*?)\\]";
// Compile the Regex.
Pattern p = Pattern.compile(regex);
// Find match between given string
// and regular expression
// using Pattern.matcher()
Matcher m = p.matcher(str);
// Get the subsequence
// using find() method
while (m.find())
{
System.out.println(m.group(1));
}
}
// Driver code
public static void main(String args[])
{
// Input String
String str = "[This is first] ignored text [This is second]";
// Function Call
printSubsInDelimeters(str);
}
}
Python3
# Python3 program to implement
# the above approach
import re
# Function to print Strings present
# between any pair of delimeters
def printSubsInDelimeters(str):
# Regex to extract the string
# between two delimiters
regex = "\\[(.*?)\\]"
# Find match between given string
# and regular expression
# using re.findall()
matches = re.findall(regex, str)
# Print the matches
for match in matches:
print(match)
# Driver code
# Input String
str = "[This is first] ignored text [This is second]"
# Function Call
printSubsInDelimeters(str)
# This code is contributed by yuvraj_chandra
This is first
This is second
时间复杂度: O(N)
辅助空间: O(N)
节省空间的方法:想法是使用正则表达式 解决这个问题。创建一个正则表达式以提取两个定界符之间的字符串,如regex =“ \\ [(。*?)\\]],然后将给定的字符串与正则表达式进行匹配。打印形成的子序列。
下面是上述方法的实现:
C++
// C++ program to implement
// the above approach
#include
#include
using namespace std;
// Function to print Strings present
// between any pair of delimeters
void printSubsInDelimeters(string str)
{
// Regex to extract the string
// between two delimiters
const regex pattern("\\[(.*?)\\]");
for(sregex_iterator it = sregex_iterator(
str.begin(), str.end(), pattern);
it != sregex_iterator(); it++)
{
// flag type for determining the
// matching behavior here it is
// for matches on 'string' objects
smatch match;
match = *it;
cout << match.str(1) << endl;
}
return;
}
// Driver Code
int main()
{
// Input String
string str = "[This is first] ignored text [This is second]";
// Function Call
printSubsInDelimeters(str);
return 0;
}
// This code is contributed by yuvraj_chandra
Java
// Java program to implement
// the above approach
import java.util.regex.*;
class GFG{
// Function to print Strings present
// between any pair of delimeters
public static void printSubsInDelimeters(String str)
{
// Regex to extract the string
// between two delimiters
String regex = "\\[(.*?)\\]";
// Compile the Regex.
Pattern p = Pattern.compile(regex);
// Find match between given string
// and regular expression
// using Pattern.matcher()
Matcher m = p.matcher(str);
// Get the subsequence
// using find() method
while (m.find())
{
System.out.println(m.group(1));
}
}
// Driver code
public static void main(String args[])
{
// Input String
String str = "[This is first] ignored text [This is second]";
// Function Call
printSubsInDelimeters(str);
}
}
Python3
# Python3 program to implement
# the above approach
import re
# Function to print Strings present
# between any pair of delimeters
def printSubsInDelimeters(str):
# Regex to extract the string
# between two delimiters
regex = "\\[(.*?)\\]"
# Find match between given string
# and regular expression
# using re.findall()
matches = re.findall(regex, str)
# Print the matches
for match in matches:
print(match)
# Driver code
# Input String
str = "[This is first] ignored text [This is second]"
# Function Call
printSubsInDelimeters(str)
# This code is contributed by yuvraj_chandra
This is first
This is second
时间复杂度: O(N)
辅助空间: O(1)