zoukankan      html  css  js  c++  java
  • LeetCode

    题目:

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

    思路:

    以第一个字符串为基准,然后循环比较

    package string;
    
    public class LongestCommonPrefix {
    
        public String longestCommonPrefix(String[] strs) {
            int len = 0;
            if (strs == null || (len = strs.length) == 0) return "";
    
            StringBuilder sb = new StringBuilder();
            int i = 0;
            int len0 = strs[0].length();
            while (i < len0) {
                char c = strs[0].charAt(i);
                for (int j = 1; j < len; ++j) {
                    if (i >= strs[j].length() || strs[j].charAt(i) != c)
                        return sb.toString();
                }
                
                sb.append(c);
                ++i;
            }
            
            return sb.toString();
        }
        
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            String[] strs = { "abc", "ab", "abcd", "abcdef" };
            LongestCommonPrefix l = new LongestCommonPrefix();
            System.out.println(l.longestCommonPrefix(strs));
        }
    
    }
  • 相关阅读:
    阅读《构建之法》1-5章
    构建之法第8,9,10章
    实验5-封装与测试2
    第六次作业-my Backlog
    保存内容
    实验四-单元测试
    实验3—修改版
    做汉堡-57号
    实验3-2
    201306114357-实验3-C语言
  • 原文地址:https://www.cnblogs.com/null00/p/5047887.html
Copyright © 2011-2022 走看看