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

}
posted @ 2020-11-30 16:16  六小扛把子  阅读(79)  评论(0编辑  收藏  举报