zoukankan      html  css  js  c++  java
  • 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
    }
    
  • 相关阅读:
    pip包安装问题
    spyder中让生成的图像单独在窗口中显示
    错误的英语提示翻译 以及经常犯的无错误
    程序结构
    运算符
    js jq计算器
    jQuery筛选选择器
    jQuery获取标签信息
    javascript的getTime函数
    animate动画
  • 原文地址:https://www.cnblogs.com/mapoos/p/13161141.html
Copyright © 2011-2022 走看看