【发布时间】:2015-07-12 14:04:32
【问题描述】:
我正在尝试实现一种算法来确定字符串是否具有所有唯一字符,而无需使用任何其他数据结构。 这是我的代码:
package CTCI;
import java.util.Scanner;
public class ArrStrng1 {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.out.println("Enter the number of characters in the string?");
int l=s.nextInt();
char[] ca=new char[l];
System.out.println("Enter the characters in the string?");
for(int i=0;i<l;i++)
{
char c=s.next().charAt(0);
ca[i]=c;
}
if(unique(ca,l))
System.out.println("YES");
else
System.out.println("NO");
s.close();
}
public static boolean unique(char[] str,int l)
{
//using insertion sort to sort the character array
char c;
for(int i=1;i<l;i++)
{
c=str[i];
int j=i;
while(j>0 && c<str[j-1])
{
str[j]=str[j-1];
j--;
}
}
//Now checking if any two consecutive characters are same
for(int j=0;j<l-1;j++)
{
if(str[j]==str[j+1])
return false;
}
return true;//If no two consecutive characters are same then the character array is unique
}
}
此解决方案不起作用,因为传递给函数 unique 的字符数组被修改,例如abcd 变成 abbb。 我错过了什么吗?我的代码中有什么错误? 任何帮助表示赞赏。谢谢。
【问题讨论】:
-
唯一改变数组的地方就是排序。将代码放在调试器中,然后找到代码在其中分配了您不期望的值。我所看到的,只要我愿意花费尽可能多的时间,您将一个字符分配给“c”,但不要将它放回数组中的任何位置。
-
尝试在内部循环中打印 str 的内容,并尝试了解程序的行为。
-
我使用了调试器,发现数组 char[] ca 输入正确,但是当它传递给函数 unique(char[] str,int l) 时,它被修改了。
-
所以在唯一的范围内调试它——让我们知道您尝试了哪些您不理解的内容。不要让我们为您调试它。
-
我不明白为什么字符数组在传递给函数时会被修改?
标签: java arrays pass-by-reference