程序媛詹妮弗
终身学习

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.

 

Solution1:  

Compare characters from top to bottom on the same column (same character index of the strings) before moving on to the next column.

 

 

 

 

code

 1 /*
 2 Time complexity : O(S), where S is the sum of all characters in all strings. 
 3 Space complexity : O(1). We only used constant extra space. 
 4 */
 5 class Solution {
 6     public String longestCommonPrefix(String[] strs) {
 7         if (strs.length == 0)  return "";
 8         for (int i = 0; i < strs[0].length(); i++) {
 9             char c = strs[0].charAt(i);
10             for (int j = 1; j < strs.length; j++) {
11                 if (i == strs[j].length() || strs[j].charAt(i) != c) { // 除str[0]外的一个String被扫完了
12                     return strs[0].substring(0, i);
13                 }
14             }
15         }
16         // 有可能strs[0]扫完了都没碰到垂直方向不相同的字符
17         return strs[0];
18     }
19 }

 

posted on 2019-04-04 14:49  程序媛詹妮弗  阅读(198)  评论(0编辑  收藏  举报