Codewars Solution:Two to One

Level 7kyu :Two to One

取2个字符串s1s2仅包含从a到的字母z

返回一个新的排序字符串,最长的字符串,包含不同的字母,

  • 每个仅取一次-来自s1或s2。

主要方法:

toCharArray()->字符串转字符数组

arraycopy(from,0,to,0,长度)->复制数组

Arrays.sort()->对数组元素进行排序

 1 import java.util.Arrays;
 2 public class TwoToOne {
 3     public static String longest (String s1, String s2) {
 4         // your code
 5         //把两个字符串拼接成一个字符串
 6         String s=s1+s2;
 7         char[] a=s.toCharArray();//字符串转字符数组
 8         char[] temp = new char[a.length];
 9         int index=0;//临时数组下标索引
10         for(int i=0;i<a.length;i++){
11           boolean flag=true;//是否重复的标志
12           for(int j=i+1;j<a.length;j++){
13             if(a[i]==a[j]){
14               flag=false; 
15               break;
16             }
17           }
18           if(flag){
19             temp[index]=a[i];//后面没有发现重复元素就赋值给临时数组
20             index++;
21           }
22         }
23         char[] newArr = new char[index];
24         System.arraycopy(temp, 0, newArr, 0, index);//复制临时到新数组
25         Arrays.sort(newArr);//引用排序函数
26         String total="";
27         for(int i=0;i<newArr.length;i++){
28           total+=newArr[i];//每个元素以字符串结果相加
29         }
30         return total;
31     }
32 }

 

posted @ 2020-05-21 23:04  慕|橙  阅读(71)  评论(0编辑  收藏  举报