zoukankan      html  css  js  c++  java
  • LeetCode记录之14——Longest Common Prefix

    本题虽然是easy难度,题目也一目了然,问题就是在这里,需要考虑的特殊情况太多,太多限制。导致我一点点排坑,浪费了较多时间。

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

      编写一个函数来查找字符串数组中最长的公共前缀字符串。


     1 class Solution {
     2     public String longestCommonPrefix(String[] strs) {
     3         int length =strs.length,strLength=0;
     4         StringBuffer sBuffer=new StringBuffer();
     5         boolean isSame=false;
     6         if(strs.length!=0)//考虑字符串数组可能为空情况
     7             strLength=strs[0].length();
     8         if (strs.length==1) {//考虑字符串数组为一个的情况
     9             return strs[0];
    10         }
    11         else{
    12             for (int i = 0; i < length - 1; i++) {
    13                 if (strs[i].length() == 0)//考虑某个字符串为空的情况
    14                     return "";
    15                 if (strLength > strs[i + 1].length())//求出最短字符串的长度
    16                     strLength = strs[i + 1].length();
    17 
    18             }
    19             for (int i = 0; i < strLength; i++) {
    20                 for (int j = 0; j < length - 1; j++) {
    21                     if (strs[j].charAt(i) == strs[j + 1].charAt(i)) {
    22                         isSame = true;
    23                     }
    24                     else{
    25                         isSame=false;
    26                     }
    27                 }
    28                 if (isSame)
    29                     sBuffer.append(strs[0].charAt(i));
    30                 else
    31                     break;
    32             }
    33             return sBuffer.toString();
    34     }
    35 }
  • 相关阅读:
    每日日报
    每日日报
    java笔记
    每日日报
    每日日报
    每日日报
    查看当前mysql时区 并设置为北京时间
    springboot 指定配置文件启动, 区分开发和线上分支
    Js Contains方法
    vue $refs的基本用法
  • 原文地址:https://www.cnblogs.com/vi3nty/p/7471809.html
Copyright © 2011-2022 走看看