zoukankan      html  css  js  c++  java
  • 【LeetCode OJ 14】Longest Common Prefix

    题目链接:https://leetcode.com/problems/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)
    	{
    		if (strs == null || strs.length == 0)
    		{
    			return "";
    		}
    		String prefix = strs[0];
    		for (int i = 1; i < strs.length; i++)
    		{
    			int j = 0;
    			while (j < strs[i].length() && j < prefix.length() && strs[i].charAt(j) == prefix.charAt(j))
    			{
    				j++;
    			}
    			if (j == 0)
    			{
    				return "";
    			}
    			prefix = prefix.substring(0, j);
    		}
    		return prefix;
    	}
    }


  • 相关阅读:
    字符串的操作
    前端
    HTML标签
    模块与包
    常用模块
    函数进阶
    函数初识
    文件操作
    集合及深浅拷贝
    python中的一些编码问题
  • 原文地址:https://www.cnblogs.com/brucemengbm/p/7048796.html
Copyright © 2011-2022 走看看