我在以下代码中遇到堆栈溢出错误…不确定我漏掉了什么?

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

I am getting stack overflow error in the following code ... not sure what am i missing here?

问题

以下是您提供的代码的翻译部分:

import java.util.Scanner;

public class RemoveDuplicates {
    public static boolean ar[] = new boolean[26];

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
        String s = sc.nextLine();
        DeDupe(s, 0, "");

    }

    public static void DeDupe(String s, int idx, String s1) {
        if (idx == s.length()) {
            System.out.println(s1);
            return;
        }
        if (ar[s.charAt(idx) - 'a'] == false) {
            s1 += s.charAt(idx);
            // System.out.print(s1);
            ar[s.charAt(idx) - 'a'] = true;
        }
        DeDupe(s, idx++, s1);
    }

}

请注意,我只提供了代码的翻译部分,没有包括问题描述或其他信息。如果您需要任何其他帮助,请随时告诉我。

英文:
import java.util.Scanner;

public class RemoveDuplicates {
	public static boolean ar[]=new boolean[26];
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc=new Scanner(System.in);
		String s=sc.nextLine();
		DeDupe(s,0,"");

	}
	public static void DeDupe(String s,int idx,String s1)
	{
		if(idx==s.length())
		{
			System.out.println(s1);
			return;
		}
		if(ar[s.charAt(idx)-'a']==false)
		{
			s1+=s.charAt(idx);
			//System.out.print(s1);
			ar[s.charAt(idx)-'a']=true;
		}
		DeDupe(s,idx++,s1);
	}

}

Trying to solve remove duplicates from string question using recursion... i am getting stack overflow error ..added the base condition not sure what am i missing

答案1

得分: 4

你在递归调用 DeDupe 时使用了 "postfix" 一元操作符。

DeDupe(s, i++, s1);

所以,实际上,i 保持为 0,并无限循环。

将其更改为 "prefix" 操作符,或者只使用 i + 1,以获得结果。

英文:

You are use the "postfix" unary operator on your recursive call to DeDupe.

DeDupe(s,i++,s1);

So, essentially, i stays at 0, and loops indefinitely.

Change it to a "prefix" operator, or just i + 1, to get a result.

答案2

得分: 0

我看到你的"DeDupe"方法是void,但是在Java中,即使String是一个对象,它也不是按引用传递的,而是按值传递的,因为String是不可变的。而且,在所有处理之后,也没有产生任何结果。

英文:

I see that "DeDupe" method of yours is void,<br>
but even the String is an object in java,<br>
it is not passed by a reference but as a value,<br>
because String is immutable.<br>
And after all the processing, no result is produced anyway.

huangapple
  • 本文由 发表于 2023年5月21日 22:25:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76300384.html
匿名

发表评论

匿名网友

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

确定