zoukankan      html  css  js  c++  java
  • LeetCode 14. Longest Common Prefix

    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.

    package LeetCode;
    
    public class L14_LongestCommonPrefix {
        public String longestCommonPrefix(String[] strs) {
            StringBuilder prefix=new StringBuilder();
            if(strs.length==0)
                return "";
            boolean flag=true;//当前循环是否有共同字母
            for(int i=0;i<strs[0].length();i++)
            {
                for(int j=1;j<strs.length;j++){//其他字符串当前位置字符是否与第一行字符串当前位置字符一致
                    if(strs[j].length()<i+1){
                        flag=false;
                        //prefix.charAt(prefix.length()-1);//移除最后一个字符
                        break;
                    }else if(strs[j].charAt(i)!=strs[0].charAt(i)){
                        flag=false;
                        break;
                    }else
                        continue;
                }
                if(!flag)
                    break;
                prefix.append(strs[0].charAt(i));
            }
            return  prefix.toString();
        }
    }
    
     
    博客园的编辑器没有CSDN的编辑器高大上啊
  • 相关阅读:
    druid spring监控配置
    深入理解Java:SimpleDateFormat安全的时间格式化
    Thread.join()方法
    static 作用
    Java链接SqlServer,学生数据管理面板
    java巅峰作业
    2019.6.12Java/IO data
    Java常用类
    2019.6.5
    java求和运算窗口5.29
  • 原文地址:https://www.cnblogs.com/flowingfog/p/9782275.html
Copyright © 2011-2022 走看看