zoukankan      html  css  js  c++  java
  • 【Leetcode】14. Longest Common Prefix

    Question:

    Write a function to find the longest common prefix string amongst an array of strings.

    LeetCode submission:

    public class Solution {
        public String longestCommonPrefix(String[] strs) {
          String ans = "";
            if (strs.length == 0 || strs == null) {
                return "";
            }
            if(strs.length==1) ans=strs[0];
            
            String min = strs[0];
    
            for (int i = 1; i < strs.length; i++) {// strs数组中字符串的个数
                //System.out.println(strs.length);
                
                while (strs[i].indexOf(min) != 0) {
                    min = min.substring(0, min.length() - 1);
                }
                ans=min;
            }
            System.out.println(ans);
            return ans;
        }
    }

    Executable code:

    public class L14 {
    
        public String longestCommonPrefix(String[] strs) {
            String ans = "";
            if (strs.length == 0 || strs == null) {
                return "";
            }
            if(strs.length==1) ans=strs[0];
            
            String min = strs[0];
    
            for (int i = 1; i < strs.length; i++) {// strs数组中字符串的个数
                //System.out.println(strs.length);
                
                while (strs[i].indexOf(min) != 0) { //当strs[]与min无法匹配时将min字符串长度减一
                    min = min.substring(0, min.length() - 1);
                }
                ans=min;
            }
            System.out.println(ans);
            return ans;
        }
    
        public static void main(String[] args) {
            L14 l14 = new L14();
            String[] strs = {"a","a","b"};
            l14.longestCommonPrefix(strs);
        }
    }

    Note:

    strs[i].indexOf(min)//返回min的第一个字符在strs[i]中的第一个位置,
     min = min.substring(0, min.length() - 1);////当strs[]与min无法匹配时将min字符串长度减一
  • 相关阅读:
    模板
    CF1271E Common Number
    模板——长链剖分
    XJOI NOIP501/511训练22 ttt学字符串
    POJ 1151 Atlantis
    BZOJ 1014 [JSOI2008]火星人prefix
    Luogu P1856 [USACO5.5]矩形周长Picture
    CF716D Complete The Graph
    Luogu P2596 [ZJOI2006]书架
    HTML 学习之JavaScript作用域
  • 原文地址:https://www.cnblogs.com/yumiaomiao/p/7062301.html
Copyright © 2011-2022 走看看