溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Longest Common Prefix之Java實現

發布時間:2020-08-14 08:10:50 來源:網絡 閱讀:417 作者:xiezh10 欄目:編程語言
一、題目

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.

二、解題思路

1、獲取數組的第一個元素firstStr作為比較的對象;
2、以firstStr的長度作為條件設定while循環;
3、從數組第二個元素開始遍歷數組,判斷每個元素是否已firstStr作為前綴;
4、如果不是,則截掉firstStr最后一個字符,再重新遍歷數組進行比較。

三、代碼實現
public String longestCommonPrefix(String[] strs) {
    if (strs.length == 0) { // 當數組長度為0時,返回空
        return "";
    } else if (strs.length == 1) {  // 當數組只有一個元素時,則返回該元素
        return strs[0];
    } else {
        String firstStr = strs[0];
        while (firstStr.length() != 0) {
            for (int i = 1; i < strs.length; i++) {
                if (strs[i].startsWith(firstStr)) {
                    if (i == strs.length -1) {
                        return firstStr;
                    }
                    continue;
                } else {
                    // 從后往前一個一個截取
                    firstStr = firstStr.substring(0, firstStr.length() - 1);
                    break;
                }
            }
        }
    }
    return "";
}
向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女