zoukankan      html  css  js  c++  java
  • Leecode no.14 求最长公共前缀

    package com.example.demo.leecode;

    import java.util.ArrayDeque;
    import java.util.Queue;

    /**
    * 最长公共前缀
    * @Date 2020/11/30
    * @author Tang
    *
    * 编写一个函数来查找字符串数组中的最长公共前缀。
    * 如果不存在公共前缀,返回空字符串 ""。
    */
    public class LongestCommonPrefix {

    /**
    * 把每个字符串分割成字符数组,遍历
    * @param strs
    * @return
    */
    public String execute(String[] strs){
    if(strs == null || strs.length == 0){
    return "";
    }

    Queue<Character> tempQueue = new ArrayDeque();
    for (char c: strs[0].toCharArray()) {
    tempQueue.add(c);
    }

    for(int i = 1; i < strs.length; i++){
    Queue<Character> queue = new ArrayDeque<>();
    if(tempQueue.isEmpty()){
    break;
    }
    for (char c: strs[i].toCharArray()) {
    if(tempQueue.isEmpty() || tempQueue.poll() != c){
    break;
    }
    queue.offer(c);
    }
    tempQueue = queue;
    }

    char[] newCharArray = new char[tempQueue.size()];
    for(int i = 0; i < newCharArray.length; i++){
    newCharArray[i] = tempQueue.poll();
    }

    return String.valueOf(newCharArray);
    }

    public static void main(String[] args) {
    String[] strs = {"abaas","abaa","abaasgf"};
    System.out.println(new LongestCommonPrefix().execute(strs));
    }

    }
  • 相关阅读:
    ubuntu下如何更改mysql数据存放路径
    collection_select
    发现星期六日的电视比较好看
    rails
    系统抢救10.04
    劫后重生,痛定思痛,ubuntu 10.04=>10.10
    随机查询N条记录
    which linux your like
    kindeditor的使用
    array
  • 原文地址:https://www.cnblogs.com/ttaall/p/14061936.html
Copyright © 2011-2022 走看看