|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- 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.
复制代码
- class Solution {
- public String longestCommonPrefix(String[] strs) {
-
- if(strs == null || strs.length == 0) return "";
-
- if(strs.length == 1) return strs[0];
-
- int len = strs.length;
-
- int index = 0;
-
- String result = "";
-
- while(true){
-
- int count = 1;
-
- for(int i = 1; i< len; i++){
-
- if(strs[i-1].length() == 0 || strs[i].length() == 0) return "";
-
- if(index +1 > strs[i-1].length() || index +1 > strs[i].length()) return result;
-
- if(strs[i-1].charAt(index) == (strs[i].charAt(index) )){
-
- count++;
- }
-
- else{
-
- return result;
- }
-
- if(count == len){
-
- result = result + strs[i].charAt(index) ;
-
- index++;
-
- }
- }
-
- }
-
- }
- }
复制代码
- class Solution {
- public String longestCommonPrefix(String[] strs) {
-
- if(strs == null || strs.length == 0) return "";
-
- String cur = strs[0];
-
- int len = strs.length;
-
- for(int i = 1; i< len; i++){
-
- while(strs[i].indexOf(cur) != 0){
-
- cur = cur.substring(0, cur.length() -1);
-
- }
- }
-
- return cur;
-
- }
- }
复制代码 |
|