如何从字符串列表中找到最长的公共后缀并在java中返回结果后缀长度?

时间:2017-08-05 04:47:44

标签: java string suffix

在ArrayList或LinkedList中考虑以下内容: [格洛斯特郡,汉普郡,约克郡,兰开夏郡] 郡是长度为5的最长公共后缀。 输出应为5 如何编写一个方法来实现上述和返回长度

2 个答案:

答案 0 :(得分:1)

试试这个。
解释在评论中

package javaapplication1;
public class SegmentTree {

    public static void main(String[] args) {
        String[] array = {"Gloucestershire", "Hampshire", "Yorkshire", "Lancashire"};
        int i,j;
        int min=10000000;

        //reversing the strings and finding the length of smallest string
        for(i=0;i<(array.length);i++)
        {
          if(array[i].length()<min)
              min=array[i].length();


         StringBuilder input1 = new StringBuilder();
         input1.append(array[i]);
         array[i] = input1.reverse().toString();
        }

        //finding the length of longest suffix

        for(i=0;i<min;i++)
        {
          for(j=1;j<(array.length);j++)
          {
              if(array[j].charAt(i)!=array[j-1].charAt(i))
              {
                break;
              }
          }
          if(j!=array.length)
              break;
        }

        System.out.println(i);
    }
}

我在这里做的是,先检查所有字符串的最后一个元素,然后查看最后一个字符串,依此类推
时间复杂度:O(n * m)
n =字符串数,m =最小字符串长度

答案 1 :(得分:0)

Guava有一个名为Strings.commonSuffix(CharSequence a, CharSequence b)的辅助函数,可以在你的算法中使用。我知道像Guava一样添加依赖只是为了让这个函数有点过分 - 在这种情况下你可以查看源代码来查看how this function is implemented,你可以将这个实现移动到你的程序中。然后你的程序看起来像这样:

import com.google.common.base.Strings;

import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class CommonSuffixLengthMain {

    public static void main(String[] args) throws IOException {

        assert 5 == commonSuffixLength(Arrays.asList("Gloucestershire", "Hampshire", "Yorkshire", "Lancashire"));

        assert 2 == commonSuffixLength(Arrays.asList("abc", "dbc", "qebc", "webc"));

        assert 0 == commonSuffixLength(Collections.emptyList());

        assert 0 == commonSuffixLength(Collections.singletonList("abc"));

        assert 0 == commonSuffixLength(Arrays.asList("abc", "def", "zxc"));
    }

    private static int commonSuffixLength(final List<String> strings) {
        int result = 0;

        if (strings == null || strings.size() < 2) {
            return result;
        }

        for (int i = 0; i < strings.size() - 1; i++) {
            String prefix = Strings.commonSuffix(strings.get(i), strings.get(i + 1));
            result = result == 0 ?
                    prefix.length() :
                    Math.min(prefix.length(), result);
        }

        return result;
    }
}