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) {
            String compare ="";
            if(strs.length == 0)
                return compare;
            
            compare = strs[0];
            for(int i = 1; i < strs.length; i++){
                int j = 0;
                while(j < compare.length() && j < strs[i].length()){
                    if(compare.charAt(j) != strs[i].charAt(j)){
                        break;
                    }
                    j++;
                }
                compare = strs[i].substring(0,j);
            }
            return compare;
        }
    }

    方法二: ref:http://www.cnblogs.com/feiling/p/3159771.html

    依次比较每个字符串的相应位置的字符,直到遇到不匹配项。可以减少不必要的比较

    public class Solution {
        public String longestCommonPrefix(String[] strs) {
             String compare = "";
             if(strs.length == 0)
                 return compare;
             
             int k = 0;
             while(true){
                 char p = ' '; 
                 int i;
                 for(i = 0; i < strs.length; i++){
                    if(k == strs[i].length())
                        break;
                         
                    if(i == 0)
                        p = strs[i].charAt(k);
                    
                     if(p != strs[i].charAt(k))
                         break;
                 }
                 
                 // 出for循环后,检查是循环结束还是break跳出的循环
                 // 如果是break跳出的循环,就break跳出while
                 if(i != strs.length)
                     break;
                 
                 compare += p;
                 k++;
             }
             
             return compare;
         }
    }
  • 相关阅读:
    平方和公式
    $bootpuss$切不掉的「水题」
    回滚莫队初步
    [***]HZOJ 柱状图
    HZOJ 走格子
    HZOJ 旋转子段
    [***]HZOJ 优美序列
    [***]HZOJ 跳房子
    HZOJ 矩阵游戏
    模板—K-D-tree(P2479 [SDOI2010]捉迷藏)
  • 原文地址:https://www.cnblogs.com/RazerLu/p/3551091.html
Copyright © 2011-2022 走看看