• 0014. Longest Common Prefix (E)


    Longest Common Prefix (E)

    题目

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

    If there is no common prefix, return an empty string "".

    Example 1:

    Input: ["flower","flow","flight"]
    Output: "fl"
    

    Example 2:

    Input: ["dog","racecar","car"]
    Output: ""
    Explanation: There is no common prefix among the input strings.
    

    Note:

    All given inputs are in lowercase letters a-z.


    题意

    找到给定字符串组的公共前缀。

    思路

    以第一个字符串中的字符为基准,再去比对其余字符串中对应位置处的字符。


    代码实现

    Java

    class Solution {
        public String longestCommonPrefix(String[] strs) {
            if (strs == null || strs.length == 0) {
                return "";
            }
            String ans = "";
            for (int i = 0; i < strs[0].length(); i++) {
                char c = strs[0].charAt(i);
                for (int j = 1; j < strs.length; j++) {
                    if (i == strs[j].length() || strs[j].charAt(i) != c) {
                        return ans;
                    }
                }
                ans += c;
            }
            return ans;
        }
    }
    

    JavaScript

    /**
     * @param {string[]} strs
     * @return {string}
     */
    var longestCommonPrefix = function (strs) {
      if (strs.length === 0) {
        return ''
      }
    
      let prefix = ''
    
      for (let i = 0; i < strs[0].length; i++) {
        let c = strs[0][i]
        for (let j = 1; j < strs.length; j++) {
          if (i === strs[j].length || strs[j][i] !== c) {
            return prefix
          }
        }
        prefix += c
      }
    
      return prefix
    }
    
  • 相关阅读:
    canvas制作倒计时炫丽效果
    MySQL存储过程
    SpringMVC入门
    JAVA面试/笔试经典题
    JAVA内存存储分配粗略讲解
    数据结构算法总结
    稳定排序
    Java集合框架
    Java笔试题及答案
    面向接口
  • 原文地址:https://www.cnblogs.com/mapoos/p/13161141.html
Copyright © 2020-2023  润新知