• leetcode longest common prefix(easy) /java


    题:

    遍历比较。

    一本正经地说一下思路。

    最长前缀。

    一旦找到一个不匹配,就无法做成最长前缀。

    所有我们的目的就是去找这个不匹配。

    注意一下字符串为空的情况,每次都会栽在这里。

    为了提高效率,找出最短字符串,因为最长前缀的长度不可能超过最短字符串的长度。

    import java.io.*;
    import java.util.*;
    
    public class Solution
    {
        public static String longestCommonPrefix(String[] strs)
        {
            String r=new String("");
            int len=strs.length;
            if(len==0)
                return r;
            int i,j;
            String temp=strs[0];
            int limit=temp.length();
            int index=0;
            for(i=1;i<len;i++)
            {
                temp=strs[i];
                if(temp.length()<limit)
                {
                    limit=temp.length();
                    index=i;
                }
    
            }
            if(limit==0)
                return r;
            char c,d;
            boolean flag=true;
    
            for(i=0;i<limit;i++)
            {
                c=strs[index].charAt(i);
                for(j=0;j<len;j++)
                {
                    d=strs[j].charAt(i);
                    if(c!=d)
                        flag=false;
    
    
                }
                if(flag==false)
                    break;
                else
                        r=r+String.valueOf(c);
            }
            return r;
        }
    
    
        public static void main(String[] args)
        {
            Scanner input=new Scanner(System.in);
            String s=new String("hz");
            String[] strs={"ca","a"};
            s=longestCommonPrefix(strs);
            System.out.println(s);
        }
    }

    哎,心累。没有用例。

  • 相关阅读:
    Codeforces 101487E
    算法笔记--2-sat
    算法笔记--图的存储之链式前向星
    算法笔记--强连通分量分解
    Uva 11995 I Can Guess the Data Structure!
    算法笔记--米勒-罗宾素数测试
    HDU 5183 Negative and Positive (NP)
    算法笔记--快读(输入外挂)模板
    POJ 3258 River Hopscotch
    HDU 2289 Cup
  • 原文地址:https://www.cnblogs.com/zhenzhenhuang/p/6842690.html
Copyright © 2020-2023  润新知