When I enter 4 abcd bcda cdab dabc, I want the result 1, but it turns out to be 4, I don't know why?
when i enter
4
abcd
bcda
cdab
dabc
I want result 1, but it turns out to be 4, I don't know why?
public class Test2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
sc.nextLine();
String[] strArr = new String[N];
for (int i = 0; i < N; i++) {
strArr[i] = sc.nextLine();
}
System.out.println(fun(strArr));
}
public static int fun(String[] arr) {
TreeSet<String> treeSet = new TreeSet<>();
for (int i = 0; i < arr.length; i++) {
char[] chars = arr[i].toCharArray();
Arrays.sort(chars);
treeSet.add(chars.toString());
}
return treeSet.size();
}
}
+3
Friday2013
source
to share
2 answers
Here is your working code:
/**
* @param args
*/
public static void main(final String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
sc.nextLine();
String[] strArr = new String[N];
// StringBuffer sb = new StringBuffer();
for (int i = 0; i < N; i++) {
strArr[i] = sc.nextLine();
}
System.out.println(fun(strArr));
}
public static int fun(final String[] arr) {
TreeSet<String> set = new TreeSet<>();
for (int i = 0; i < arr.length; i++) {
char[] chars = arr[i].toCharArray();
Arrays.sort(chars);
set.add(new String(chars));
}
return set.size();
}
The problem is that you can see that the toString of characters gives you a representation of the memory address. so you end up with 4 elements, as this is always a new instance of the same string.
+3
kism3t
source
to share
You are using treeSet.add(chars.toString());
, which actually refers to Object.toString()
, which formats the array as something like [C@39ed3c8d
.
If you are using:
treeSet.add(Arrays.toString(chars));
the lines will look like [a, b, c, d]
which should then do what you want.
+1
OldCurmudgeon
source
to share