Write a function to find the longest common prefix string array. (A day to prevent dementia)

topic:

Write a function to find the longest common prefix string array.

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

Example 1:

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

Input: [ "dog", "racecar ", "car"]
Output: ""
Explanation: there is no input common prefix.
Description:

All input contains only lowercase letters az.

 

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/longest-common-prefix
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

 

 

package com.wxp.Dynamicprogramming;
/**
 * 字符串的最长公共前缀
 * @author amarsoft
 *
 */
public class Leetcode14 {
    public static void main(String[] args) {
        String [] s = {"dog","racecar","car"};
    String result =    longestCommonPrefix(s);
    System.out.println(result);
    }
    public static String longestCommonPrefix(String[] strs) {
        if(strs.length==0) {
            return "";
        }
        TEMP String 
     * method two, less run timeSTRs = [0]; // get the first character is a temporary array 
        for ( int I = 0; I <strs.length; I ++ ) {
             int J = 0 ;
             // loop and a second comparator comparing after the common portion, and in a third comparison string is the entire array longest common portion. 
            for (; J <temp.length () && J <STRs [I] .length (); J ++ ) {
                 IF (! temp.charAt (J) = STRs [I] .charAt (J)) {
                     BREAK ; 
                } 
            } 
            TEMP temp.substring = (0 , J); 
        } 
     return TEMP; 
 } 
    / **
     * @Param STRs 
     * @return 
     * / 
     public String longestCommonPrefix2 (String [] STRs) {
             IF (strs.length == 0) return "" ; 
            String STR = STRs [0 ];
             for ( int I =. 1; I <STRs .length; I ++ ) {
                 the while (STRs [I] .indexOf (STR) = 0! ) { 
                    STR = str.substring (0, str.length () -. 1); // If the string does not match the length minus one continue 
                    } 
                } 
                return STR; 
            } 
    
}

Guess you like

Origin www.cnblogs.com/hnwxp/p/12145000.html