zoukankan      html  css  js  c++  java
  • 14. 最长公共前缀

    14. 最长公共前缀

    题目:https://leetcode-cn.com/problems/longest-common-prefix/description/

    package com.test;
    
    public class Lesson014 {
        public static void main(String[] args) {
            String[] strs = new String[]{};
            String prefix = longestCommonPrefix(strs);
            System.out.println(prefix);
        }
    
        private static String longestCommonPrefix(String[] strs) {
            if (strs.length == 0) {
                return "";
            }
            // 默认公共前缀是第一个字符串
            String res = strs[0];
            for (int i = 1; i < strs.length; i++) {
                // 获取每个字符串
                String current = strs[i];
                int j = 0;
                // 获取循环的最大数值
                int length = Math.min(res.length(), current.length());
                for (; j < length; j++) {
                    String res01 = res.substring(j, j + 1);
                    String current01 = current.substring(j, j + 1);
                    if (!res01.equals(current01)) {
                        break;
                    }
                }
                // 每一次循环修正公共前缀
                res = res.substring(0, j);
            }
            return res;
        }
    }
  • 相关阅读:
    [比赛|考试]9.21上午考试
    给花_Q
    [比赛|考试] 9.17下午考试
    [比赛|考试]nowcoder NOIP提高组组第二场
    图论
    生成函数
    P4197 Peaks
    3942: [Usaco2015 Feb]Censoring
    P2245 星际导航
    P3565 [POI2014]HOT-Hotels
  • 原文地址:https://www.cnblogs.com/stono/p/9468071.html
Copyright © 2011-2022 走看看