zoukankan      html  css  js  c++  java
  • 【leetcode刷题笔记】Longest Common Prefix

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


    题解:以strs[0]为模板,每次挨个查看是否所有的串里面是否第i位上都和strs[0]一样,如果都一样,把i位置上的字符放到answer里面,i++,继续循环,否则返回当前的answer。

    代码如下:

     1 public class Solution {
     2     public String longestCommonPrefix(String[] strs) {
     3         if(strs == null || strs.length == 0)
     4             return "";
     5         
     6         StringBuffer answer = new StringBuffer();
     7         for(int i = 0;i < strs[0].length();i++){
     8             char now = strs[0].charAt(i);
     9             for(int j = 1;j < strs.length;j++){
    10                 if(i>strs[j].length()-1 || strs[j].charAt(i) != now)
    11                     return answer.toString();
    12             }
    13             answer.append(now);
    14         }
    15         return answer.toString();
    16     }
    17 }
  • 相关阅读:
    Flask--目录
    Linux相关目录
    Mac 提示错误”xcrun: error“
    subprocess模块
    压缩模块
    GitPython模块
    Ansible-ansible命令
    YAML语法
    Ansible-安装
    Ansible-概念
  • 原文地址:https://www.cnblogs.com/sunshineatnoon/p/3858812.html
Copyright © 2011-2022 走看看