zoukankan      html  css  js  c++  java
  • LeetCode:Longest Common Prefix

    Longest Common Prefix

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

    Solution:

    public class Solution {
        public String longestCommonPrefix(String[] strs) {
            // Start typing your Java solution below
            // DO NOT write main() function
            int n = strs.length;
            if(n==0) return "";
            int i=0;
            for(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 strs[0].substring(0,i);
                }
            }
            return strs[0].substring(0,i);
        }
    }
    

     以字符串个数作为外循环

    class Solution {
    public:
        string longestCommonPrefix(vector<string> &strs) {
            // Note: The Solution object is instantiated only once and is reused by each test case.
         if (strs.size() == 0) {
             return "";
         }
         int longest_common_prefix_len = strs[0].size();
         for (int i = 1; i < strs.size(); ++i) {
             for (int j = 0; j < longest_common_prefix_len; ++j) {
                 if (strs[i][j] != strs[0][j]) {
                     longest_common_prefix_len = j;
                 }
             }
         }
         return strs[0].substr(0,longest_common_prefix_len);
        }
    };
    
  • 相关阅读:
    Git笔记
    Android笔记
    个人人生警示
    Java 注解
    JAVA面试题
    kotlin学习笔记
    Android Studio之gradle和gradle插件
    gcc在Linux下编译so文件出错 jni.h: no such file or directory
    apktool新官网地址
    Vim 使用记录
  • 原文地址:https://www.cnblogs.com/yeek/p/3813925.html
Copyright © 2011-2022 走看看