Maximum product prefix string

后端 未结 3 1185
死守一世寂寞
死守一世寂寞 2021-01-01 02:48

The following is a demo question from a coding interview site called codility:

A prefix of a string S is any leading contiguous part of S. For example

3条回答
  •  醉话见心
    2021-01-01 03:05

    public class Main {
        public static void main(String[] args) {
            String input = "abababa";
            String prefix;
            int product;
            int maxProduct = 0;
            for (int i = 1; i <= input.length(); i++) {
                prefix = input.substring(0, i);
                String substr;
                int occurs = 0;
                for (int j = prefix.length(); j <= input.length(); j++) {
                    substr = input.substring(0, j);
                    if (substr.endsWith(prefix))
                        occurs++;
                }
                product = occurs*prefix.length();
                System.out.println("product of " + prefix + " = " +
                    prefix.length() + " * " + occurs +" = " + product);
                maxProduct = (product > maxProduct)?product:maxProduct;
            }
            System.out.println("maxProduct = " + maxProduct);
        }
    }
    

提交回复
热议问题