Leetcode exercises Longest Common Prefix

Question:

Longest Common Prefix

Write a function to find the longest common prefix string amongst an array of strings.

If there is no common prefix, return an empty string "".

Example 1:

Input: ["flower","flow","flight"]
Output: "fl"

Example 2:

Input: ["dog","racecar","car"]
Output: ""

Explanation: There is no common prefix among the input strings.
Note:

All given inputs are in lowercase letters a-z.

My solution is thinking:

Comparison of a first and second i-alphabet characters, if the first letter of the i-th and the second character the same, the second and third i th letter, if equal, letters will be added to the i-th final str, the size of i is from 0 until the last cycle.

The problem is:

class Solution {
    public String longestCommonPrefix(String[] strs) {
      
        int Strslength = strs.length;


        if(Strslength>1)
        {

            int minLength = strs[0].length();
            //O(n)
            for(String str:strs)
            {
                int strLength = str.length();
                if(minLength > strLength)
                {
                    minLength = strLength;
                }
            }

            //Store output ;
            String str = "";


           label:for(int i=0;i<minLength;i++)
            {

                for(int j=1;j<strs.length;j++)
                {

                    if((strs[j-1].charAt(i))!=(strs[j].charAt(i)))
                    {

                            break label;
                        
                    }

                }

            str+= strs[0].charAt(i);
            }
            return str;

        }
        else if(Strslength==1)
        {
            return strs[0];
        }
        else
        {
            return "";
        }

       

       
    }
}

Others solution:

In this solution, the authors found that mainly through two string values are equal, and then returns the result as a string and continue to look for use indexOf function, first find an equal position.

    public static String longestCommonPrefix(String[] strs) {
            if(strs.length==0){return "";}
            String  prefix = strs[0];
            for(int i=1;i<strs.length;i++)
            {
                while (strs[i].indexOf(prefix)!=0)
                {
                    prefix= prefix.substring(0,prefix.length()-1);
                }
            }

            return prefix;
    }

Guess you like

Origin www.cnblogs.com/zhichun/p/12063586.html
Recommended