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

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

    即找出一组字符串的最长公共前缀。

    public class Solution {
        public String longestCommonPrefix(String[] strs) {
            int min_size = Integer.MAX_VALUE;
            int n = strs.length;
            if(n == 0){
                return "";
            }
            for(int i = 0;i < n;i++){
                //若存在空串则返回"";
                if(strs[i].length() == 0){
                    return "";
                }
                if(strs[i].length()<min_size){
                    min_size = strs[i].length();//求得最短串的长度
                }
            }
            String re="";
            for(int j = 0;j < min_size;j++){
                char c = strs[0].charAt(j);
                for(int k = 0;k < n;k++){
                    if(strs[k].charAt(j)!=c){
                        return re;
                    }
                }
                re = re+c;
            }
            return re;
            
        }
    }
  • 相关阅读:
    leetcode297
    leetcode4
    leetcode23
    leetcode72
    leetcode239
    leetcode42
    leetcode128
    leetcode998
    SAP MM GR-based IV, 无GR不能IV?
    小科普:机器学习中的粒子群优化算法!
  • 原文地址:https://www.cnblogs.com/mrpod2g/p/4263828.html
Copyright © 2011-2022 走看看