codeWars刷题day02

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

题目

1、Your order, please

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.

Examples
“is2 Thi1s T4est 3a” --> “Thi1s is2 3a T4est”
“4of Fo1r pe6ople g3ood th5e the2” --> “Fo1r the2 g3ood 4of th5e pe6ople”
“” --> “”

我的方案:

import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Order {
  public static String order(String words) {
    // ...
    if(words.length() == 0){
      return words;
    }
    String line = "";
    String[] str = words.split(" ");
    int j = 1;
    for(String s : str){
      for(int i = 0 ; i < str.length; i++){
        String regx = "[^0-9]";
        Pattern p = Pattern.compile(regx);
        Matcher m = p.matcher(str[i]);
        String index = m.replaceAll("").trim();
        if(Integer.valueOf(index) == j){
          line += str[i] + " ";
          j++;
          break;
        }
        }
    }
    return line.trim();
  }
}

别人的解题方案:

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();
  }
}

别人的解题方案优雅简洁,stream流来遍历,Comparator.comparing来进行排序,想法差不多,但是代码更整洁好看,要学会优化自己的代码,使其整洁优雅。


2、最高得分词

给定一串单词,您需要找到得分最高的单词。

单词的每个字母根据其在字母表中的位置得分:a = 1, b = 2, c = 3等等。

例如,分数abad为8(1 + 2 + 1 + 4)。

您需要将得分最高的单词作为字符串返回。

如果两个单词得分相同,则返回原始字符串中最早出现的单词。

所有字母均为小写,所有输入均有效
我的解题:

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class Kata {

  public static String high(String s) {
    // Your code here...
    
     String[] s1 = s.split(" ");
        List<String> collect = Arrays.stream(s1).sorted(Comparator.comparing(
                a -> {
                    int num = 0;
                    for (char c : a.toString().toCharArray()) {
                        int value = c - 96;
                        num += value;
                    }
                    return num;
                }
        ).reversed()).collect(Collectors.toList());
    
    return collect.get(0);
  }

}

别人的解题:

import java.util.*;

public class Kata {
  public static String high(String s) {
    return Arrays.stream(s.split(" "))
                .max(Comparator.comparingInt(
                        a -> a.chars().map(i -> i - 96).sum()
                )).get(); 
  }
}

使用stream流直接获取值最大的字符串,更简洁优雅。


Good vs Evil

Description
Middle Earth is about to go to war. The forces of good will have many battles with the forces of evil. Different races will certainly be involved. Each race has a certain worth when battling against others. On the side of good we have the following races, with their associated worth:

Hobbits: 1
Men: 2
Elves: 3
Dwarves: 3
Eagles: 4
Wizards: 10
On the side of evil we have:

Orcs: 1
Men: 2
Wargs: 2
Goblins: 2
Uruk Hai: 3
Trolls: 5
Wizards: 10
Although weather, location, supplies and valor play a part in any battle, if you add up the worth of the side of good and compare it with the worth of the side of evil, the side with the larger worth will tend to win.

Thus, given the count of each of the races on the side of good, followed by the count of each of the races on the side of evil, determine which side wins.

Input:
The function will be given two parameters. Each parameter will be a string of multiple integers separated by a single space. Each string will contain the count of each race on the side of good and evil.

The first parameter will contain the count of each race on the side of good in the following order:

Hobbits, Men, Elves, Dwarves, Eagles, Wizards.
The second parameter will contain the count of each race on the side of evil in the following order:

Orcs, Men, Wargs, Goblins, Uruk Hai, Trolls, Wizards.
All values are non-negative integers. The resulting sum of the worth for each side will not exceed the limit of a 32-bit integer.

Output:
Return “Battle Result: Good triumphs over Evil” if good wins, “Battle Result: Evil eradicates all trace of Good” if evil wins, or “Battle Result: No victor on this battle field” if it ends in a tie.

我的解题方案:

import java.util.Arrays;
import java.util.stream.IntStream;

public class GoodVsEvil {
  public static String battle(String goodAmounts, String evilAmounts) {
    int[] goodWorth = new int[]{1, 2, 3, 3, 4, 10};
        int[] evilWorth = new int[]{1, 2, 2, 2, 3, 5, 10};
        int[] good = Arrays.stream(goodAmounts.split(" ")).mapToInt(i -> Integer.parseInt(i)).toArray();
        int[] evil = Arrays.stream(evilAmounts.split(" ")).mapToInt(i -> Integer.parseInt(i)).toArray();
        int goodSum = IntStream.rangeClosed(0,good.length-1).map(i->good[i]*goodWorth[i]).sum();
        int evilSum = IntStream.rangeClosed(0,evil.length-1).map(i->evil[i]*evilWorth[i]).sum();
        return goodSum > evilSum ?  "Battle Result: Good triumphs over Evil"  : (
                evilSum > goodSum ? "Battle Result: Evil eradicates all trace of Good" :
                                    "Battle Result: No victor on this battle field");                                                     
  }
}

这道题需要仔细阅读题目,一直通不过测试用例,原来是题目理解错了,理解了题目意思是很简单的一道题目。

总结

codeWars刷题第二天,在上班空余时间刷刷算法题目,学习别人的代码写法,优雅好看,也学到了很多,充实自己很辛福。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值