如何将两个有重复字符在内的字符串合并成一个,并且排序

时间:2022-03-19 10:26:10

例如:a=”xyaabbbccccdefww”,b=”xxxxyyyyabklmopqwxy”;
longest(a,b) => “abcdefklmonpqwxy”
1.

import java.util.TreeSet
public class TowtoOne{
public static String longest(s1,s2){
char[] chars;
String result="";
TreeSet<Character> t1 = new TreeSet<Character>();
TreeSet<Character> t2 = new TreeSet<Character>();
chars = s1.toCharArray();
for(char s:chars){
t1.add(s);
}
chars = s2.toCharArray();
for(char s:chars){
t2.add(s);
}
t1.addAll(t2);
for(char c:t1){
result +=c;
}
result;
}
}

通过声明2个treeset集合,将字符取出后,添加到集合中,treeset自动实现对字符的排序。

2.

public class TowtoOne{
public static String longest(String s1,String s2){
String s = s1+s2;
int[] alp = new int[26];
StringBuffer sb = new StringBuffer();
for(int i=0;i<sb.length();i++){
alp[s.charAt(i)-'a'] = 1;
}
for(int i=0;i<alp.length;i++){
if(alp[i]==1)res.append((char)('a'+1));
}
return sb.toString();
}
}