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));
    }

    }
  • 相关阅读:
    使用NSTask调用shell
    《UML和模式应用》读书笔记(一)
    iOS网络编程
    多线程
    Quartz2D
    沙盒中的数据存取
    UIButton设置为圆形按钮并增加边框
    Mac开发快速入门
    JavaWeb学习总结(三)response与request
    JavaWeb学习总结(二) Servlet
  • 原文地址:https://www.cnblogs.com/ttaall/p/14061936.html
Copyright © 2011-2022 走看看