美文网首页
Your order, please

Your order, please

作者: Magicach | 来源:发表于2017-12-26 15:52 被阅读0次

    Your task is to sort a given string. Each word in the String will contain a single number. This number is the position the word should have in the result.

    Note: Numbers can be from 1 to 9. So 1 will be the first word (not 0).

    If the input String is empty, return an empty String. The words in the input String will only contain valid consecutive numbers.

    For an input: "is2 Thi1s T4est 3a" the function should return "Thi1s is2 3a T4est"

    your_order("is2 Thi1s T4est 3a")
    [1] "Thi1s is2 3a T4est"

    Good Solution1:

    import java.util.Arrays;
    import java.util.Comparator;
    
    public class Order {
      public static String order(String words) {
        return Arrays.stream(words.split(" "))
          .sorted(Comparator.comparing(s -> Integer.valueOf(s.replaceAll("\\D", ""))))
          .reduce((a, b) -> a + " " + b).get();
      }
    }
    

    Good Solution2:

    import java.util.Arrays;
    public class Order {
      public static String order(String words) {
            String[] strs = words.split(" ");
            Arrays.sort(strs, (String s1, String s2) -> s1.replaceAll("[a-zA-Z]","").compareTo(s2.replaceAll("[a-zA-Z]",""))  );
            String f = "";
            for(String st:strs) f+=st + " ";
            return f.substring(0,f.length()-1);
        }
    }
    

    相关文章

      网友评论

          本文标题:Your order, please

          本文链接:https://www.haomeiwen.com/subject/vzkjgxtx.html