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

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

    思路: 逐个遍历

    第一趟: 第一个子串与第二个子串 求prefix。 备注。 prefix的最大长度等于两个子串中最短的字符串长度。

    第二趟: 把第一趟的结果作为子串与第三个子串比较,以此类推

    备注: java基础: String, StringBuilder ,StringBuffer 的区别及使用。 http://www.cnblogs.com/A_ming/archive/2010/04/13/1711395.html

    public class Solution {
        public String longestCommonPrefix(String[] strs) {
            if(strs == null || strs.length == 0) {
                return "";
            }
            if(strs.length == 1) {
                return strs[0];
            }
            int size = strs.length;
            String tmp = strs[0];
            
            for(int i = 1; i < size; i++ ) {
                int k = Math.min(strs[i].length(),tmp.length());
                StringBuilder sb = new StringBuilder();
                for(int t = 0 ; t < k; t++) {
                    if(strs[i].charAt(t) == tmp.charAt(t)) {
                        sb.append(strs[i].charAt(t));
                    } else {
                        break;
                    }
                }
                tmp = sb.toString();
            }
            return tmp;
        }
    }
    

      

  • 相关阅读:
    CSS——清除浮动
    .net 多线程之线程取消
    .net 多线程临时变量
    NPOI helper
    添加学员存储过程
    SQL-sqlHelper001
    ado.net 中事务的使用
    T-SQL 事务2
    T-SQL 事务
    T-SQL 带参数存储过程
  • 原文地址:https://www.cnblogs.com/superzhaochao/p/6377120.html
Copyright © 2011-2022 走看看