Two to One

最近换了项目做,跟开发相差有点大了  发现自己不会写代码了 为了让自己多学点 开始在code war上练题了,从简单的开始 争取一天一题   锻炼自己开发同时巩固知识

Take 2 strings s1 and s2 including only letters from ato z. Return a new sorted string, the longest possible, containing distinct letters,

  • each taken only once - coming from s1 or s2.

Examples:

a = "xyaabbbccccdefww"
b = "xxxxyyyyabklmopq"
longest(a, b) -> "abcdefklmopqwxy"

a = "abcdefghijklmnopqrstuvwxyz"
longest(a, a) -> "abcdefghijklmnopqrstuvwxyz"




import java.util.Arrays;

public class Main {

    public static void main(String[] args) {
        String a = "xyaabbbccccdefww";
        String b = "xxxxyyyyabklmopq";

        System.out.print("\n"+longest(a,b));
    }
    public static String longest (String s1, String s2) {
        // your code
        String tmp;
        String output="";
        if (!s1.isEmpty()&&!s2.isEmpty()){
            tmp=s1.equals(s2)?s1:s1+s2;

            char[] chars=tmp.toCharArray();
            Arrays.sort(chars);
            output=String.valueOf(chars[0]);
            for (int i=1;i<tmp.length();i++)
            {
               // System.out.print("char[i]="+String.valueOf(chars[i])+"output="+output);
                if (!String.valueOf(chars[i]).equals(output.substring(output.length()-1)))
                {
                    output+=chars[i];
                }
            }
        }
        return output;
    }
}

 

 

发现其他人的解决办法比自己的好太多了,也要简洁很多呀!!

他人一:

public class TwoToOne { public static String longest (String s1, String s2) { String s = s1 + s2; return s.chars().distinct().sorted().collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString(); } }

二:

public class TwoToOne { public static String longest (String s1, String s2) { StringBuilder sb = new StringBuilder(); (s1 + s2).chars().distinct().sorted().forEach(c -> sb.append((char) c)); return sb.toString(); } }

 

三:

public static String longest (String s1, String s2) { String all = "abcdefghijklmnopqrstuvwxyz"; return all.replaceAll("[^" + s1+s2 + "]", ""); }

。。。。。。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值