【Codewars】Shortest Word

Codewars裏的 7kyu Kata。

題目說明:

Simple, given a string of words, return the length of the shortest word(s).

String will never be empty and you do not need to account for different data types.

使用雙指針解題,很簡單,但是需要注意結束循環後需要在次進行計算取值。

解題代碼:

import java.util.Arrays;

public class Kata {
    public static int findShort(String s) {
        int i = 0, j = i + 1;
        int res = s.length();
        if(res > 1 && s.charAt(j) == ' ')
            return 1;
        int length = s.length();
        while(j < length){
            if(s.charAt(j) != ' ') {
                j++;
            } else {
                res = res > j - i ? j - i : res;
                i = j + 1;
                j = j + 1;
            }
        }
        res = res > j - i ? j - i : res;
        return res;
    }
}

Test Case:

import org.junit.Test;

import java.util.Arrays;
import java.util.Random;
import java.util.stream.Collectors;

import static org.junit.Assert.assertEquals;

/**
 * Created by Javatlacati on 01/03/2017.
 */
public class KataTest {
    @Test
    public void findShort() throws Exception {
        assertEquals(3, Kata.findShort("bitcoin take over the world maybe who knows perhaps"));
        assertEquals(3, Kata.findShort("turns out random test cases are easier than writing out basic ones"));

        assertEquals(3, Kata.findShort("lets talk about Java the best language"));
        assertEquals(1, Kata.findShort("i want to travel the world writing code one day"));
        assertEquals(2, Kata.findShort("Lets all go on holiday somewhere very cold"));
    }

    public static int sol(String s) {
        return Arrays.stream(s.split(" ")).mapToInt(c -> c.length()).min().getAsInt();
    }

    String[] names = new String[]{"Bitcoin", "LiteCoin", "Ripple", "Dash", "Lisk", "DarkCoin", "Monero", "Ethereum", "Classic", "Mine", "ProofOfWork", "ProofOfStake", "21inc", "Steem", "Dogecoin", "Waves", "Factom", "MadeSafeCoin", "BTC"};

    @Test
    public void randomTests() throws Exception {
        Random r = new Random();
        int tam = r.nextInt(names.length);
        String a = Arrays.stream(names).unordered().skip(names.length - tam).collect(Collectors.joining(" "));
        assertEquals(sol(a), Kata.findShort(a));
    }
}

個人總結:

沒有考慮循環退出後,漏判了最後一個單詞,造成部分錯誤。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章