Codewars Java练习:Consecutive strings

题目

You are given an array strarr of strings and an integer k. Your task is to return the first longest string consisting of k consecutive strings taken in the array.

#Example:

longest_consec([“zone”, “abigail”, “theta”, “form”, “libe”, “zas”, “theta”, “abigail”], 2) –> “abigailtheta”

n being the length of the string array, if n = 0 or k > n or k <= 0 return “”.

题解

算是中规中矩的一道题吧

import java.util.*;
import java.io.*;

class LongestConsec {

    public static String longestConsec(String[] ss, int k) {
		if (k < 0)
			k = 0;
		if (ss.length < k)
			return "";
		int len_arr[] = new int[ss.length+1];
		len_arr[0] = 0;
		for (int i=0;i<ss.length;i++)
			len_arr[i+1] = len_arr[i] + ss[i].length();
		int pos = -1, bst_ans = -1;
		for (int i=0;i+k-1<ss.length;i++) {
			if (len_arr[i+k] - len_arr[i] > bst_ans) {
				bst_ans = len_arr[i+k] - len_arr[i];
				pos = i+k-1;
			}
		}
		String result = new String();
		for (int i=pos-k+1;i<=pos;i++)
			result += ss[i];
		return result;
    }
};

 

发表评论

电子邮件地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据