英文:
Remove pairs of nested brackets anywhere in a string in Java
问题
这是您的代码,我将代码部分保持不变:
public class PairRemoval {
    public static void main(String[] args) {
        String text = "hello [ [ ] hello ] hello [ hello ] hello hello";
        String leftPattern = "[";
        String rightPattern = "]";
        String sentence = pairRemoval(text, leftPattern, rightPattern);
        System.out.println(sentence);
    }
    public static String pairRemoval(String text, String leftPattern, String rightPattern) {
        int count = 0;
        String sentence = "";
        int leftIndex = 0;
        int rightIndex = text.length() - 1;
        while (leftIndex <= rightIndex) {
            char leftLetter = text.charAt(leftIndex);
            char rightLetter = text.charAt(rightIndex);
            if (leftLetter == leftPattern.charAt(0)) {
                count++;
                leftIndex++;
                continue;
            }
            if (rightLetter == rightPattern.charAt(0)) {
                if (count > 0) {
                    count--;
                    rightIndex--;
                    continue;
                }
            }
            sentence = sentence + leftLetter;
            leftIndex++;
        }
        return sentence;
    }
}
这段代码的目标是移除成对的括号。如果您有其他问题或需要进一步的帮助,请随时提出。
英文:
I'm working on a school assignment and I can't manage to figure out. I've tried several different approaches to this including searching from the left, inside to out, and this is outside to in. I searched for over an hour online and on S.O.
I'm very new to programming so perhaps I just don't know what to look for or maybe this is too advanced for me just yet. I feel like I am missing something in my logic itself. If anyone can explain the logic, I would appreciate the patience.
Note: I have permission from my teacher to use Stack Overflow. If I'm doing this wrong here, please correct me and teach me how to make better posts- thank you.
The GOAL is to remove pairs of brackets. For instance:
This:
hello [ [ ] hello ] hello [ hello ] hello hello
Should result in this:
hello hello hello hello hello hello
And This:
] hello world ] ] [ HELLO ] WORLD ] ] ] hello world
Should result in this:
hello world ] ] HELLO ] WORLD ] ] ] hello world
This is my code:
    public class PairRemoval {
        public static void main(String[] args) {
            String text = "] hello world ] ] [ HELLO ] WORLD ] ] ] hello world";
            String leftPattern = "[";
            String rightPattern = "]";
    
            String sentence = pairRemoval(text, leftPattern, rightPattern);
    
            System.out.println(sentence);
            // Expected:  hello world ] ] HELLO ] WORLD ] ] ] hello world (per assignment)
            // Output:  ] hello world ] ] HELLO ] WORLD ] ] ] hello world
        }
        
        public static String pairRemoval(String text, String leftPattern, String rightPattern) {
    
            int count = 0;
            String sentence = "";
            int leftIndex = 0; // Initialize left index to search from the beginning of the string
            int rightIndex = text.length() - 1; // Initialize right index to search from the end of the string
        
            // Loop until the left and right indexes meet or cross each other
            while (leftIndex <= rightIndex) {
                char leftLetter = text.charAt(leftIndex);
                char rightLetter = text.charAt(rightIndex);
        
                // If the left letter matches the left pattern
                if (leftLetter == leftPattern.charAt(0)) {
                    count++;
                    leftIndex++;
                    continue; // Skip to next iteration to keep searching from the left
                }
        
                // If the right letter matches the right pattern
                if (rightLetter == rightPattern.charAt(0)) {
                    if (count > 0) {
                        count--;
                        rightIndex--;
                        continue; // Skip to next iteration to keep searching from the right
                    }
                }
        
                // If neither letter matches a pattern, append the left letter to the sentence
                sentence = sentence + leftLetter;
                leftIndex++;
               
            }
        
            // Return the final sentence with all pairs removed
            return sentence;
        }
Edit: Added example input output
text = 'hello [ [ ] hello ] hello [ hello ] hello hello'
left pattern = '['
right pattern = ']'
Expected value was: 'hello hello hello hello hello hello'
text = '> hello hello > > < hello > hello > > > hello hello'
left pattern = '<'
right pattern = '>'
Expected value was: ' hello hello > > hello > hello > > > hello hello'
text = '< < hello > hello hello hello > < hello < hello < > hello'
left pattern = '<'
right pattern = '>'
Expected value was: ' hello hello hello hello hello < hello < hello'
text = '[ [ [ hello [ [ hello hello hello hello [ [ ] ] hello hello'
left pattern = '['
right pattern = ']'
Expected value was: ' [ hello [ [ hello hello hello hello [ [ hello hello'
Example 1: 
text = { { hello } } { } hello hello } hello hello hello hello 
leftPattern =  {
rightPattern = }
expected = hello     hello hello } hello hello hello hello
Example 2: 
text = hello ( hello hello hello ) hello ) ) ) hello
leftPattern =  (
rightPattern = )
expected =. hello  hello hello hello  hello ) ) ) hello
Example 3: 
text = hello hello } { hello { } hello } { { hello
leftPattern =  {
rightPattern = }
expected = hello hello   hello   hello   { hello
答案1
得分: 1
你可以通过计算字符串中每种括号的数量,并通过移除相同数量的括号对来迭代字符串来实现这个目标。
算法:
str = "hello [ [ ] hello ] hello [ hello ] hello"
lcount = str.count('[')
rcount = str.count(']')
minimum = min(lcount, rcount) // 给出括号对的数量
lcount = minimum // 需要移除的左括号数量
rcount = minimum // 需要移除的右括号数量
for i in str:
    if (str[i] == '[' && lcount != 0):
        移除 str[i];
        lcount--;
    else if (str[i] == ']' && rcount != 0):
        移除 str[i];
        rcount--;
Java 实现:
import static java.lang.Math.min;
class Main{
    public static void main(String[] args){
        String str = "] hello world ] ] [ HELLO ] WORLD ] ] ] hello world";
        String newStr = "";
        int lcount = str.length() - str.replace("[", "").length();
        int rcount = str.length() - str.replace("]", "").length();
        
        lcount = rcount = min(lcount, rcount);
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == '[' && lcount != 0) {
                lcount--;
            }
            else if (str.charAt(i) == ']' && rcount != 0){
                rcount--;
            }
            else{
                newStr += str.charAt(i);
            }
        }
        System.out.println(newStr);
    }
}
输出:
hello world ] ]  HELLO ] WORLD ] ] ] hello world
英文:
You can do this by counting the number of each type of brackets in the string and iterate over the string by removing common number of pairs.
The algorithm:
str = "hello [ [ ] hello ] hello [ hello ] hello"
lcount = str.count('[')
rcount = str.count(']')
minimum = min(lcount, rcount) //Gives the number of pairs
lcount = minimum //Number of left brackets to be removed
rcount = minimum //Number of right brackets to be removed
for i in str:
	if (str[i] == '[' && lcount != 0):
		remove str[i];
		lcount--;
	else if (str[i] == ']' && rcount != 0):
		remove str[i];
		rcount--;
The java implementation:
import static java.lang.Math.min;
class Main{
    public static void main(String[] args){
        String str = "] hello world ] ] [ HELLO ] WORLD ] ] ] hello world";
        String newStr = "";
        int lcount = str.length() - str.replace("[", "").length();
        int rcount = str.length() - str.replace("]", "").length();
        
        lcount = rcount = min(lcount, rcount);
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == '[' && lcount != 0) {
                lcount--;
            }
            else if (str.charAt(i) == ']' && rcount != 0){
                rcount--;
            }
            else{
                newStr += str.charAt(i);
            }
        }
        System.out.println(newStr);
    }
}
Output:
hello world ] ]  HELLO ] WORLD ] ] ] hello world
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论