删除Java中字符串中的任何位置的嵌套括号对。

huangapple go评论66阅读模式
英文:

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 = &quot;] hello world ] ] [ HELLO ] WORLD ] ] ] hello world&quot;;
            String leftPattern = &quot;[&quot;;
            String rightPattern = &quot;]&quot;;
    
            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 = &quot;&quot;;
            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 &lt;= 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 &gt; 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 = &#39;hello [ [ ] hello ] hello [ hello ] hello hello&#39;
left pattern = &#39;[&#39;
right pattern = &#39;]&#39;
Expected value was: &#39;hello hello hello hello hello hello&#39;

text = &#39;&gt; hello hello &gt; &gt; &lt; hello &gt; hello &gt; &gt; &gt; hello hello&#39;
left pattern = &#39;&lt;&#39;
right pattern = &#39;&gt;&#39;
Expected value was: &#39; hello hello &gt; &gt; hello &gt; hello &gt; &gt; &gt; hello hello&#39;

text = &#39;&lt; &lt; hello &gt; hello hello hello &gt; &lt; hello &lt; hello &lt; &gt; hello&#39;
left pattern = &#39;&lt;&#39;
right pattern = &#39;&gt;&#39;
Expected value was: &#39; hello hello hello hello hello &lt; hello &lt; hello&#39;

text = &#39;[ [ [ hello [ [ hello hello hello hello [ [ ] ] hello hello&#39;
left pattern = &#39;[&#39;
right pattern = &#39;]&#39;
Expected value was: &#39; [ hello [ [ hello hello hello hello [ [ hello hello&#39;

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 = &quot;hello [ [ ] hello ] hello [ hello ] hello&quot;

lcount = str.count(&#39;[&#39;)
rcount = str.count(&#39;]&#39;)

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] == &#39;[&#39; &amp;&amp; lcount != 0):
		remove str[i];
		lcount--;
	else if (str[i] == &#39;]&#39; &amp;&amp; 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 = &quot;] hello world ] ] [ HELLO ] WORLD ] ] ] hello world&quot;;
        String newStr = &quot;&quot;;

        int lcount = str.length() - str.replace(&quot;[&quot;, &quot;&quot;).length();
        int rcount = str.length() - str.replace(&quot;]&quot;, &quot;&quot;).length();
        
        lcount = rcount = min(lcount, rcount);

        for (int i = 0; i &lt; str.length(); i++) {
            if (str.charAt(i) == &#39;[&#39; &amp;&amp; lcount != 0) {
                lcount--;
            }
            else if (str.charAt(i) == &#39;]&#39; &amp;&amp; rcount != 0){
                rcount--;
            }
            else{
                newStr += str.charAt(i);
            }
        }

        System.out.println(newStr);
    }
}

Output:

hello world ] ] HELLO ] WORLD ] ] ] hello world

huangapple
  • 本文由 发表于 2023年3月7日 12:53:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/75658162.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定