codeWars的一道题目而已

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.*;
class LongestConsec {
    
    public static String longestConsec(String[] strarr, int k) {
        
        // 特殊情况
        int strarrLenth = strarr.length;
        if(strarrLenth == 0 || k > strarrLenth || k <= 0){
          return "";
        }
        //创建一个List和StringBuffer
        List list = new ArrayList();
        StringBuffer s1 = new StringBuffer();
        
        for(int i = 0; i < strarrLenth; i ++){
           //根据给定的k值,也就是连续加字符串的个数,来确定循环次数
           if(i < (strarrLenth-(k-1)) ){
              //循环一次就依次将strarr字符串合适位置的字符串取出来,加到StringBuffer s1上
              for(int j = k; j > 0; j --){  
                  s1.append(strarr[i - (j-k)]); 
              //根据k值拼接好的字符串,赋值给list(这里如果list不行,不知道原因)
              if(s1.length() != 0 && j == 1){
                  list.add(s1.toString());
              }    
            }   
            //将使用完的s1,删除所有元素,以免影响下次使用
            s1.setLength(0);
            }
         }    
          
        String temp = "";
        int num = 0;
        //取出最长字符串
        for(int j = 0; j < list.size(); j ++){
           String ss = list.get(j);
           if(list.get(j).length() > temp.length()){
               temp = list.get(j);
               num = j;
               System.out.println(num);
               System.out.println(list.get(j));
           }
        }
        return list.get(num);
    }
}

别人的解法

class LongestConsec {
    public static String longestConsec(String[] strarr, int k) {
        if (strarr.length == 0 || k > strarr.length || k <= 0)
            return "";

        String longestStr = "";
        for (int index = 0; index < strarr.length - k + 1; index++) {
            StringBuilder sb = new StringBuilder();
            for (int i = index; i < index + k; i++) {
                sb.append(strarr[i]);
            }
            if (sb.toString().length() > longestStr.length()) {
                longestStr = sb.toString();
            }
        }
        return longestStr;
    }
}


 
  



你可能感兴趣的:(疑难杂症)