LeetCode 14. Longest Common Prefix

原题链接在这里:https://leetcode.com/problems/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.

题解:

strs中的第一个字符串从i = 0 开始,取char, 取出char后,用来比较其他所有字符串strs[j],若是此时index i 已经等于strs[j]字符串的长度 或者 strs[j]字符创相应位置 i 上的char不同,说明已经走不下去了,就地返回strs[0].substring(0,i). 

最后走完了strs[0]跳出了外层loop, 就返回strs[0], 因为此时已经走完了strs[0]的长度了.

Time Complexity: O(m*n), m 是字符串的数量, m = strs.length, n是最短字符串的长度.

Space: O(1), regardless res.

AC Java:

 1 public class Solution {
 2     public String longestCommonPrefix(String[] strs) {
 3         if(strs == null || strs.length == 0){
 4             return "";
 5         }
 6         for(int i = 0; i<strs[0].length(); i++){
 7             for(int j = 1; j<strs.length; j++){
 8                 if(strs[j].length() == i || strs[j].charAt(i) != strs[0].charAt(i)){
 9                     return strs[0].substring(0,i);
10                 }
11             }
12         }
13         return strs[0];
14     }
15 }

 

posted @ 2015-09-18 10:28  Dylan_Java_NYC  阅读(189)  评论(0编辑  收藏  举报