• 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 }
  • 相关阅读:
    『软件介绍』SQLServer2008 基本操作
    PCA的数学原理
    PCA的数学原理
    Oracle数据处理
    UVa 11995
    Unreal Engine 4 C++ 为编辑器中Actor创建自己定义图标
    codecombat之边远地区的森林1-11关及地牢38关代码分享
    初识ecside
    how tomcat works读书笔记 七 日志记录器
    HDU 1754(线段树区间最值)
  • 原文地址:https://www.cnblogs.com/xpang0/p/7471809.html
Copyright © 2020-2023  润新知