最長公共前綴_最長的公共前綴

最長公共前綴

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.pswp.cn/news/540670.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/540670.shtml
英文地址,請注明出處:http://en.pswp.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; } …