牛牛有N个字符串,他想将这些字符串分类,他认为两个字符串A和B属于同一类需要满足以下条件:
A中交换任意位置的两个字符,最终可以得到B,交换的次数不限。比如:abc与bca就是同一类字符串。
现在牛牛想知道这N个字符串可以分成几类。
首先输入一个正整数N(1 <= N <= 50),接下来输入N个字符串,每个字符串长度不超过50。
输出一个整数表示分类的个数。
4 abcd abdc dabc bacd
1
import java.util.*;
public class StringClassify {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
String[] str = new String[N];
HashSet set = new HashSet();
for (int i = 0; i < N; i++) {
str[i] = sortStr(sc.next());
set.add(str[i]);
}
System.out.println(set.size());
}
public static String sortStr(String str) {
char[] chars = str.toCharArray();
Arrays.sort(chars);
return new String(chars);
}
}
import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
public class TestDemo5
{
public static void main(String [] args)
{
int count=StrinClassifaction();
System.out.println(count);
}
//字符串分类方法
public static int StrinClassifaction()
{
Scanner scanner=new Scanner(System.in);
int num=scanner.nextInt();
String [] str=new String[num];
for(int i=0;i<num;i++)
{
str[i]=mySort(scanner.next());
}
HashSet<String> set = new HashSet<String>();
for(int i=0;i<str.length;i++)
{
set.add(str[i]);
}
return set.size();
}
//给字符串中的字符排序
public static String mySort(String str)
{
char [] ch=str.toCharArray();//将字符串转成数组
Arrays.sort(ch);//数组排序
return String.copyValueOf(ch);//将数组专程字符串返回
}
}
先转成char[]再排序,然后比较char[],相同的删除,剩下的size就是个数
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNextInt()) {
int n = in.nextInt();
int[][] count = new int[n][26];
String[] str = new String[n];
for (int i = 0; i < n; i++) {
str[i] = in.next();
}
for (int i = 0; i < n; i++) {
char[] array = str[i].toCharArray();
for (int j = 0; j < array.length; j++) {
count[i][array[j] - 'a']++;
}
}
HashSet set = new HashSet<String>();
for (int j = 0; j < n; j++) {
String s = new String();
for (int i = 0; i < 26; i++) {
s += count[j][i];
}
set.add(s);
}
System.out.println(set.size());
}
}
}