zoukankan      html  css  js  c++  java
  • longest-common-prefix


    /**
    *编写一个函数来查找字符串数组中的最长公共前缀。
    * 如果不存在公共前缀,返回空字符串 ""。
    * 说明: 所有输入只包含小写字母 a-z 。
    */

    /**
     *编写一个函数来查找字符串数组中的最长公共前缀。
     * 如果不存在公共前缀,返回空字符串 ""。
     * 说明: 所有输入只包含小写字母 a-z 。
     */
    
    public class Main53 {
        public static void main(String[] args) {
            String[] strs = {};
            System.out.println(Main53.longestCommonPrefix(strs));
        }
    
        public static String longestCommonPrefix(String[] strs) {
            if (strs == null || strs.length < 1) {
                return "";
            }
            String result = strs[0];
            for(int i=1; i<strs.length; i++){
                if(!strs[i].startsWith(result)){
                    result = result.substring(0, result.length()-1);
                    i--;
                    // 新的字符串以 整个result 开头的话继续循环下去
                    // 新的字符串不以 整个result 开头的话就将result这个字符串最后一位砍掉,并再次比较。
                }
            }
            return result;
        }
    }
    

      

  • 相关阅读:
    C# 线程之间切换
    工厂方法(创建型)
    单例模式(创建型)
    HTTP请求超时
    命令模式
    Asp.Net Core EF Migrations(二)
    Asp.Net Core EF Migrations
    Vue父子组件之间的通讯(学习笔记)
    数组的方法(笔记)
    Vue-router入门
  • 原文地址:https://www.cnblogs.com/strive-19970713/p/11356321.html
Copyright © 2011-2022 走看看