iT邦幫忙

2025 iThome 鐵人賽

DAY 5
0
生成式 AI

Chatting with ChatGPT——一天學習一題Leetcode系列 第 5

美好星期五-14. Longest Common Prefix

  • 分享至 

  • xImage
  •  

明天就是星期六了!!
今天來學一個有趣的LeetCode吧!!
今天題目大意: 給一組字串,找出「最長共同開頭」。

例子:
["flower","flow","flight"] → "fl"
["dog","racecar","car"] → ""

直觀做法:先假設第一個字串就是答案,然後跟其他字串一個一個比:
如果共同部分縮短,就更新答案,最後剩下的就是最長共同的字母。

class Solution {
    public String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0) {
            return "";
        }

        // 先假設第一個字串是答案
        String prefix = strs[0];

        // 跟其他字串一個一個比
        for (int i = 1; i < strs.length; i++) {
            // 找出 prefix 和當前字串的共同部分
            while (strs[i].indexOf(prefix) != 0) {
                // 不斷縮短 prefix
                prefix = prefix.substring(0, prefix.length() - 1);
                if (prefix.isEmpty()) {
                    return "";
                }
            }
        }
        return prefix;
    }
}


上一篇
D-4 LeetCode 13. Roman to Integer
下一篇
Day6-LeetCode 20. Valid Parentheses
系列文
Chatting with ChatGPT——一天學習一題Leetcode9
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言