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 }
  • 相关阅读:
    Java的Set集合中的retainAll()方法
    蒲丰投针问题
    根据贝叶斯公式求解三门问题
    概率论公式(续)
    数字(number)
    寻找最美的你(select)
    木棍
    lowbit
    搜索题
    day7
  • 原文地址:https://www.cnblogs.com/sunshineatnoon/p/3858812.html
Copyright © 2011-2022 走看看