欧美一区二区三区老妇人-欧美做爰猛烈大尺度电-99久久夜色精品国产亚洲a-亚洲福利视频一区二区

LongestCommonPrefix之Java實現(xiàn)

一、題目

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.

10年積累的網(wǎng)站設(shè)計、做網(wǎng)站經(jīng)驗,可以快速應對客戶對網(wǎng)站的新想法和需求。提供各種問題對應的解決方案。讓選擇我們的客戶得到更好、更有力的網(wǎng)絡服務。我雖然不認識你,你也不認識我。但先網(wǎng)站設(shè)計后付款的網(wǎng)站建設(shè)流程,更有海棠免費網(wǎng)站建設(shè)讓你可以放心的選擇與我們合作。

二、解題思路

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

三、代碼實現(xiàn)
public String longestCommonPrefix(String[] strs) {
    if (strs.length == 0) { // 當數(shù)組長度為0時,返回空
        return "";
    } else if (strs.length == 1) {  // 當數(shù)組只有一個元素時,則返回該元素
        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 "";
}

網(wǎng)站名稱:LongestCommonPrefix之Java實現(xiàn)
網(wǎng)頁URL:http://www.chinadenli.net/article24/ihhhce.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供動態(tài)網(wǎng)站外貿(mào)網(wǎng)站建設(shè)移動網(wǎng)站建設(shè)微信公眾號全網(wǎng)營銷推廣響應式網(wǎng)站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

綿陽服務器托管