最长公共前缀_最长的公共前缀

最长公共前缀

Problem statement:

问题陈述:

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

编写函数以在字符串数组中找到最长的公共前缀字符串

If there is no common prefix, return an empty string "".

如果没有公共前缀,则返回一个空字符串“”

Solution:

解:

Input Example:

输入示例:

    Example 1:
Let the set of strings to be {"flower", "fly", "flow"}
The longest common prefix is "fl"
Example 2:
Let the set of strings to be {"dog", "donkey", "door", "cat"}
The longest common prefix is "", i.e., empty string. 
Since there is no common prefix at all. 

最长的公共前缀 (Longest common prefix)

Longest common prefix simply means the longest prefix (prefix is a substring also, but not vice-versa) all the member strings consist of.

最长公共前缀仅表示所有成员字符串组成的最长前缀(前缀也是子字符串,反之亦然)。

查找一组字符串的最长公共前缀的算法 (Algorithm to find longest common prefix of a set of strings)

Solving particularly for two string, the problem is not that difficult what it is for a set of strings. But we can simply break the problem into sub-problems where we can solve for only two strings and simply pass the output for further string processing 's. In a simple word, the whole thing can be formulated to be:

特别是对于两个字符串,解决的问题并不像一组字符串那么困难。 但是我们可以简单地将问题分解为几个子问题,在这些子问题中,我们只可以解决两个字符串,然后将输出传递给进一步的字符串处理。 简而言之,整个事情可以表述为:

    LongestCommonPrefix(string1, string2, ..., string n)
=   LongestCommonPrefix(LongestCommonPrefix(string1,string2),string3,...,string n)
=   LongestCommonPrefix(newstring1,string3,string4,...,string n)
=   ...
=   LongestCommonPrefix(newstring n-1, string n)
=   new string n = final result

So this simply converts the problem for a set of 
strings to a problem of two strings only

Finding longest common prefix for two strings (string x, string y)

查找两个字符串(字符串x,字符串y)的最长公共前缀

  1. Check for base case

    检查基本情况

  2. IF anyone is empty string
    return empty string;
    
    
  3. Declare result as an empty string;

    将结果声明为空字符串;

  4.     IF string x is smaller than y
    //check for common prefix part on basis of x
    FOR( i=0;i<length of string x; i++)
    IF(x[i]==y[i])
    result+=x[i]; //append the common character
    ELSE//no common character at this point
    Returnresult
    END FOR
    ELSE//if string y is smaller than x
    //check for common prefix part on basis of y		
    FOR (i=0;i<length of y; i++)
    IF(y[i]==x[i])
    result+=y[i];//append the common character
    ELSE//no common character at this point
    return result;
    END FOR
    END IF-ELSE
    
    
  5. result consist of longest common prefix for these two strings

    结果由这两个字符串最长公共前缀组成

Explanation with example

举例说明

    Let's consider the first example
The set of strings: {"flower", "fly", "flow"}
LongestCommonPrefix("flower", "fly", "flow")
=   LongestCommonPrefix(LongestCommonPrefix ("flower","fly"),"flow")
=   LongestCommonPrefix("fl", "flow")
=   "fl"
Let's consider the second example
the set of strings to be {"dog", "donkey", "door", "cat"}
LongestCommonPrefix("dog", "donkey", "door", "cat")
=   LongestCommonPrefix(LongestCommonPrefix ("dog", "donkey"),"door", "cat")
=   LongestCommonPrefix("do","door", "cat")
=   LongestCommonPrefix (LongestCommonPrefix("do", "door") , "cat")
=   LongestCommonPrefix("do", "cat")
=   "" //empty string

C++ implementation

C ++实现

#include <bits/stdc++.h>
using namespace std;
string findPrefix(string x,string y){
//base case checking
if(x=="" || y=="")
return "";
string result="";
//if string x is smaller than y
if(x.length()<y.length()){
//check up for common prefix part
for(int i=0;i<x.length();i++){
if(x[i]==y[i])
result+=x[i];
}
}
else{
//if string y is smaller than x
for(int i=0;i<y.length();i++){
//check up for common prefix part 
if(y[i]==x[i])
result+=y[i];
else
return result;
}
}
return result;
}
string longestCommonPrefix(vector<string>& strs) {
//base cases
if(strs.size()==0)
return "";
//if only one string exists
if(strs.size()==1)
return strs[0];
string prefix=strs[0];
//follow the associative property for checking 
//take two strings each time & pass output prefix 
//as one string for further processings
for(int i=1;i<strs.size();i++){
prefix=findPrefix(prefix,strs[i]);
if(prefix=="")
return prefix;
}
return prefix;
}
int main(){
int n;
cout<<"enter no of strings you want to add\n";
cin>>n;
string s;
vector<string> v;
cout<<"enter "<<n<<" strings\n";
//collect input
while(n--){
cin>>s;
v.push_back(s);
}
//print longest common prefix
if(longestCommonPrefix(v)=="")
cout<<"no common prefix between the strings\n";
else
cout<<"longest common prefix: "<<longestCommonPrefix(v)<<endl;
return 0;
}

Output

输出量

First run:
enter no of strings you want to add
3
enter 3 strings
flower
fly
flow
longest common prefix: fl
Second run:
enter no of strings you want to add
4
enter 4 strings
dog
donkey
door
cat
no common prefix between the strings

翻译自: https://www.includehelp.com/icp/longest-common-prefix.aspx

最长公共前缀

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/540670.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

物联网听起来像是一个和互联网不同的网,万物互联又把网给弄丢了,正向我们扑面而来的是万物互联网。...

物联网听起来像是一个和互联网不同的网&#xff0c;"万物互联"又把"网"给弄丢了&#xff0c;正向我们扑面而来的是"万物互联网"。转载于:https://www.cnblogs.com/beingonline/p/7484135.html

sdram trp_TRP的完整形式是什么?

sdram trpTRP&#xff1a;电视收视点 (TRP: Television Rating Point) TRP is an abbreviation of "Television Rating Point". TRP是“电视评分点”的缩写 。 It is a system or standard of measurement which signifies the demand and popularity of a televisi…

Controller计算值传到jsp页面,用session传值

HttpSession session request.getSession(); session.setAttribute("key",value); jap 用 ${key}来接收该值 转载于:https://www.cnblogs.com/douder/p/7484491.html

CBT的完整形式是什么?

CBT&#xff1a;基于计算机的培训 (CBT: Computer Based Training) CBT is an abbreviation of "Computer-based training". CBT是“基于计算机的培训”的缩写 。 It is a training program which entails the use of a personal system or networked computer. The…

论道社会化商业

主持人 用友优普副总裁傅毅&#xff1a; 谢谢各位嘉宾&#xff0c;我们会留一些时间让在座的嘉宾提问。请各位嘉宾用一个非常简单的一句话&#xff0c;或者几个关键词&#xff0c;总结一下你认为的社会化商业是什么&#xff1f; 用友优普执行总裁 徐洋&#xff1a; 社会化商业为…

CChelper彩虹SDK可视远程客服解决方案

本文讲的是 : CChelper彩虹SDK可视远程客服解决方案 , 在智能生态产业链中&#xff0c;智能硬件终端是把握消费者的直接环节&#xff0c;随着物联网时代迈向成熟&#xff0c;智能家居领域的硬件逐渐成为智能硬件终端的主角。目前的市场环境下&#xff0c;智能家居领域的自身硬…

matlab 简介_MATLAB简介

matlab 简介MATLAB简介 (MATLAB Introduction) MATLAB was designed by Cleve Moler for his student in 1970s but after some time jack little, an engineer realized its potential and rewrote it at the MathWorks, and it was rewritten in C language by the date of 1…

Scala中的嵌套循环

Scala中的嵌套循环 (Nested loop in Scala) In programming, a nested loop is used in initializing or iterate multi-dimensional array or to print patterns. Scala provides an efficient method to use nested loops in the programming language. The most used nested…

python基础-字典

字典 # 字典是python基本数据结构之一&#xff0c;相对于列表和元组&#xff0c;他是无序的&#xff0c;每次输出都打乱了顺序&#xff0c;没有下标hello{110:{"name":"alex","age":28,"home":"shandong"},111:{"name&…

sql算术运算符_SQL中的算术运算符

sql算术运算符SQL | 算术运算符 (SQL | Arithmetic Operators) Different number-crunching administrators are utilized in SQL to be specific Addition (), Subtraction (-), Multiplication (*), Division (/), Modulus (%). SQL中使用了不同的数字运算管理员来表示特定的…

HDU 6188 Duizi and Shunzi

栈。 将数字排序后&#xff0c;一个一个压入栈。如果栈顶两个元素形成了对子&#xff0c;那么$ans1$&#xff0c;弹出栈顶两个元素&#xff1b;如果栈顶三个元素形成了顺子&#xff0c;那么$ans1$&#xff0c;弹出栈顶三个元素。 #include<bits/stdc.h> using namespace …

php 单例模式有什么缺点_PHP的完整形式是什么?

php 单例模式有什么缺点PHP&#xff1a;超文本预处理器 (PHP: Hypertext Preprocessor ) PHP is an abbreviation of Hypertext Preprocessor, earlier called Personal Home Page. PHP is extensively used HTML-embedded, open-source server-side scripting language create…

Myeclipse有关的问题

Myeclipse配置问题 1.行数显示 window ----preference----General-----Editors-----TextEditors----show line numbers 2.编码设置 window ---preference----workspace-----设置 3.jsp编码设置 window ---preference----myeclipse------Files And Editors------jsp 4.jsp的视图…

weak-to-strong-generalization始终比母体更智能的人工智能,能否被它的母体所监管supervision,从而变的更强

正如supervison这个词&#xff0c;就像就是母亲对孩子的超级super愿景vision&#xff0c;比母亲更聪明更强&#xff0c;也就意味着要按照母亲期望的那样成长&#xff0c;不合理的行为要能够纠正supervison。 一代比一代强&#xff0c;一代比一代好。 弱模型监督能否激发出更强…

最小跳数

Description: 描述&#xff1a; This problem is a standard interview problem which has been featured in interview rounds of Adobe, Amazon, Oyo rooms etc. 此问题是标准的采访问题&#xff0c;已在Adobe&#xff0c;Amazon&#xff0c;Oyo房间等的采访回合中出现。 P…

《Web安全之机器学习入门》一 第3章 机器学习概述

第3章 机器学习概述机器学习的概念非常多&#xff0c;从有监督到无监督&#xff0c;从聚类到回归&#xff0c;从浅层学习到深度学习&#xff0c;从准确率到召回率&#xff0c;它们究竟是什么意思呢&#xff1f;本章将介绍最主要的几个概念。不少机器学习初学者甚至包括业内老司…

ue 抗锯齿 渲染序列失灵_最大的锯齿形序列

ue 抗锯齿 渲染序列失灵Problem statement: 问题陈述&#xff1a; Given a square matrix of size n x n, find the sum of the Zigzag sequence with the largest sum. A zigzag sequence starts from the top and ends at the bottom. Two consecutive elements of sequence…

团队-团队编程项目作业名称-成员简介及分工

成员&#xff1a;祁昊 分工&#xff1a;ui设计&#xff0c;美工&#xff0c;详细设计。转载于:https://www.cnblogs.com/qihao10086/p/7496101.html

python身份运算符_Python身份运算符

python身份运算符Identity operators are used to perform the comparison operation on the objects i.e. these operators check whether both operands refer to the same objects (with the same memory location) or not. 身份运算符用于对对象执行比较操作&#xff0c;即…

Oracle-Decode()函数和CASE语句的不同

Oracle-Decode()函数和CASE语句的区别&#xff1a; 具体示例如下&#xff1a; 1.CASE语句&#xff1a; SELECT CASE SIGN(5 - 5) WHEN 1 THEN Is Positive WHEN -1 THEN Is Negative ELSE Is Zero END FROM DUAL; 后台实现&#xff1a; if (SIGN(5 – 5) 1) { Is Positive; } …