DailyChallenge

14 The longest public prefix

Easy20200614

Topic describes

Write a function to find the longest public prefix in an array of strings.

Returns the empty string “” if no public prefix exists.

Example 1:

Input:"flower"."flow"."flight"]
Output:"fl"
Copy the code

Example 2:

Input:"dog"."racecar"."car"]
Output:""
Explanation: The input does not have a common prefix.Copy the code

Description:

All inputs contain only lowercase letters A-z.

Solution

Iterate through each string in turn, updating the longest public prefix, and save the string with StringBuilder. Just iterate over the length of the RES each time.

class Solution {
    public String longestCommonPrefix(String[] strs) {
        StringBuilder res = new StringBuilder();
        int len = strs.length;
        if( len == 0) { return "";  }else if(len == 1) { return strs[0];  }else{  for(int i = 0; i < Math.min(strs[0].length(), strs[1].length()); i++){  if(strs[0].charAt(i) ! = strs[1].charAt(i)){  break;  }else{  // System.out.println(res);  res.append(strs[0].charAt(i));  }  }  for(int j = 2; j < len; j++){  if(strs[j].length() < res.length()){  res.delete(strs[j].length(), res.length());  }  for(int i = 0; i < res.length(); i++){  if(res.charAt(i) ! = strs[j].charAt(i)){ res.delete(i,res.length());  break;  }  }  }   }  return res.toString();   } } Copy the code

My official account is GitKid

Temporarily share LeetCode every day, I am in the process of continuous learning, the public account is also constantly enriched, welcome everyone to scan code attention.

Wechat official account

This article is formatted using MDNICE