题目:Write a function to find the longest common prefix string amongst an array of strings.
翻译:求一个字符串数组中 共同的最长前缀。
思路:以第一个串为基准,逐个位置遍历,并遍历字符串数组,如果出现某个字符串长度小于当前位置,或者出现当前位置的字符不相同,返回字串strs[0].substring(0,pos);思路很简单。
代码:
public String longestCommonPrefix(String[] strs) {
int count = strs.length;//字符串的个数
int pos = 0;//当前指针位置
if (count == 0||strs[0].length()==0) //判断空
return "";
for(; pos < strs[0].length();pos++)
{
for(int j = 1; j < count;j++)
{
if(strs[j].length()<=pos||strs[0].charAt(pos)!=strs[j].charAt(pos))//超过长度,或者不相等
return strs[0].substring(0, pos); //返回字串
}
}
return strs[0];
}
分享到:
相关推荐
LeetCode Longest Common Prefix解决方案
c语言 c语言_c语言编程基础之leetcode题解第14题最长公共前缀
c++ c++_c++编程基础之leetcode题解第14题最长公共前缀.zip
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. Java AC 版本
编写一个函数来查找字符串数组中的最长公共前缀。如果不存在公共前缀,返回空字符串 ""。示例 1:输出: "fl"示例 2:输出: ""解释: 输入不存在公共前缀
Given a string, find the length of the longest substring without repeating characters. Examples: Given "abcabcbb", the answer is "abc", which the length is 3. Given "bbbbb", the answer is "b", with...
最长公共前缀 20 Valid Parentheses 有效的括号 26 Remove Duplicates from Sorted Array 删除排序数组中的重复项 32 Longest Valid Parentheses 最长有效括号 33 Search in Rotated Sorted Array 搜索旋转排序数组 ...
给你一个字符串 s,请你返回它的 最长快乐前缀。 如果不存在满足题意的前缀,则返回一个空字符串。 示例 1: 输入:s = level 输出:l 解释:不包括 s 自己,一共有 4 个前缀(l, le, lev, leve)和 4 个后缀(l, el...
c# c#_Leetcode面试题解之第14题最长公共前缀
python python_leetcode面试题解之第14题最长公共前缀
leetcode中文版 LeetCode # Title Chinese Tag Solution 1 Two Sum ...最长公共前缀 string 16 3Sum Closest 最接近的三数之和 two pointers,array 21 Merge Two Sorted Lists 合并两个有序链表 lin
c语言 C语言_C语言编程基础之leetcode题解第5题最长回文子串
c++ c++_c++编程基础之leetcode题解第5题最长回文子串
c++ c++_c++编程基础之leetcode题解第32题最长的有效括号
java面试 java面试_leetcode面试题解之第14题最长公共前缀_编程
LeetCode674. 最长连续递增序列674. 最长连续递增序列解题思路:记录每次递增序列的长度,max存储最大长度// 递增序列更新最大长度} else
答案LeetCode-Longest_Substring_Without_Repeating_Characters 这是LeetCode上“最长子串无重复字符”问题的解决方案。 问题描述:给定一个字符串,求没有重复字符的最长子串的长度。 示例 1:输入:“abcabcbb” ...
leetcode卡 TrieTree 前缀树 Leetcode > 探索 > 前缀树卡片 一共5个题(除去之前卡片重复的题)
找出字符串中最长的没有重复字符的子串,算法精巧,代码简洁