0

I try to solve the problem 14 on leetcode, which is to write a function to find the longest common prefix string amongst an array of strings. Here is my code, the result I expect is "f" while the result I got is "". Can someone help me out here? Thanks!

 class Solution {
    String[] strsa={"fsd","fds","fgsdgf","fggdgdgd"};
    String prefix=longestCommonPrefix(strsa); 
    public String longestCommonPrefix(String[] strs) {

        if (strs == null || strs.length == 0) {
            return "";
        }

        String result = strs[0];
        for (int i = 1; i < strs.length; i++) {
            while (strs[i].indexOf(result) != 0) {
                result = result.substring(0, result.length() - 1);
            }
        }

        return result;

     }
     }

Here is the result enter image description here

Xinyi Li
  • 123
  • 1
  • 2
  • 8

1 Answers1

0

You're input is showing an empty array. "[]" I also get an error: Error: Line 13: error: missing return statement.

I think it's an issue with their website.

RickyM
  • 867
  • 6
  • 7
  • Thanks! But do you know why the input is empty? – Xinyi Li Dec 20 '17 at 23:26
  • Isn't is supposed to take the " String[] strsa={"fsd","fds","fgsdgf","fggdgdgd"};" – Xinyi Li Dec 20 '17 at 23:27
  • I don't know how they are implementing the Solution class. Normally the Application class with the main method would pass in the String array either hard coded or from user input. There might be something missing from what's provided. What you have works but it won't run on it's own. I believe the Java compiler looks for the main method first unless specified. – RickyM Dec 20 '17 at 23:45
  • I found hackerrank.com to be a better way of learning algorithms outside of a class setting. – RickyM Dec 21 '17 at 00:25