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.

    这题的意思是,求字符串数组中的所有字符串的公共头。

    解题思路:由于要求所有字符串的公共头,和求几个整数的公约数一样。我们先将字符串数组中的相邻元素进行比较,取出相同的部分,放入一个TreeMap中,其中TreeMap的key为相同部分字符串的长度,值为相同部分的字符串。最后取出最小的key即可。

    class Solution {
        public String longestCommonPrefix(String[] strs) {
             int len=strs.length;
            if(len==0)
                return "";
            if(len==1)
                return strs[0];
            TreeMap<Integer,String> topMap=new TreeMap<Integer,String>();
            for(int i=1;i<len;i++)
            {
                String str1=strs[i-1];
                String str2=strs[i];
                int num=0;
                if(str1.length()>str2.length())
                {
                     num=str2.length();
                }
                else
                {
                     num=str1.length();
                }
                String top="";  //两个字符串相同的部分
                for(int j=0;j<num;j++)
                {
                    if(str1.charAt(j)==str2.charAt(j))
                    {
                        top+=str1.charAt(j);
                    }
                    else
                    {
                        break;
                    }
                }
                topMap.put(top.length(), top);//TreeMap如果不进行特殊处理的话,默认升序排列
                
            }
            int key=topMap.firstKey();  
            return topMap.get(key);
        }
    }
  • 相关阅读:
    ue4 Windows RawInput Plugin
    UE4 VR中一种比较清晰的UI制作方式
    C# 自定义特性及反射
    C# 委托
    java+orace+hql分页
    数据库小知识总结
    往oracle数据库表中插入五十万条数据
    jsp页面传到action乱码问题
    常见数据库对象与java.sql.Types对照
    Oracle数据库初探
  • 原文地址:https://www.cnblogs.com/contixue/p/7827417.html
Copyright © 2011-2022 走看看