【leetcode刷题笔记】Longest Common Prefix

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


 

题解:以strs[0]为模板,每次挨个查看是否所有的串里面是否第i位上都和strs[0]一样,如果都一样,把i位置上的字符放到answer里面,i++,继续循环,否则返回当前的answer。

代码如下:

 1 public class Solution {

 2     public String longestCommonPrefix(String[] strs) {

 3         if(strs == null || strs.length == 0)

 4             return "";

 5         

 6         StringBuffer answer = new StringBuffer();

 7         for(int i = 0;i < strs[0].length();i++){

 8             char now = strs[0].charAt(i);

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

10                 if(i>strs[j].length()-1 || strs[j].charAt(i) != now)

11                     return answer.toString();

12             }

13             answer.append(now);

14         }

15         return answer.toString();

16     }

17 }

你可能感兴趣的:(LeetCode)