简体   繁体   English

找出两个字符串的最长公共前缀

[英]Find the longest common prefix of two strings

I want to find the longest common prefix of two strings.我想找到两个字符串的最长公共前缀。 Is there a way to loop my last couple of if statements so that I can end at the last characters that do not match each other?有没有办法循环我的最后几个 if 语句,以便我可以在最后一个不匹配的字符处结束?

System.out.println("Enter the first string: ");
String s = input.nextLine();

System.out.println("Enter the second string: ");
String s2 = input.nextLine();

//check if first characters are same
if (s.charAt(0) != s2.charAt(0)) {
  System.out.println(""+s+ " and "+s2+ " have no common prefix");
  System.exit(0);
    }

if (s.charAt(0) == s2.charAt(0))
  System.out.print(" "+s.charAt(0));

if (s.charAt(0) == s2.charAt(0))
  System.out.print(" "+s.charAt(1));

if (s.charAt(0) == s2.charAt(0))
  System.out.print(" "+s.charAt(2));  
  }
}

Example:例子:

Enter first string: Welcome to c++

Enter second string: Welcome to java

The code should return Welcome to as the common prefix.该代码应返回Welcome to作为公共前缀。

Maybe something like:也许是这样的:

int sLength = s.length(),
    s2Length = s2.length(),
    minLength = (sLength < s2Length) ? sLength : s2Length;

for (int i = 0; i < minLength; i++) {
    if (s.charAt(i) == s2.charAt(i)) {
        System.out.println(s.charAt(i));
    }
    else {
        break;
    }
}

But more details about your question would be great.但是有关您的问题的更多详细信息会很棒。

Edit: It depends what @afrojuju_ wants to do.编辑:这取决于@afrojuju_ 想要做什么。 That's not clear.这还不清楚。 Some more logic may be added to accomplish the desired behavior.可以添加一些更多的逻辑来完成所需的行为。

Edit 2: Added string length comparison as pointed out by @JavaBeast.编辑 2:添加了@JavaBeast 指出的字符串长度比较。

try this.尝试这个。 I guess this is what you are trying to achieve.我想这就是你想要达到的目标。 If this is correct I will add explanation later如果这是正确的,我稍后会添加解释

import java.util.*;
import java.lang.*;
import java.io.*;

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        String s = "Hello Wo";
        String s2 = "Hello World";
        String small,large;
         if(s.length() > s2.length()) 
            {small = s2;large = s;}
          else
            {small = s;large = s2;}
        int index = 0;    
        for(char c: large.toCharArray())
        {
            if(index==small.length()) break;
            if(c != small.charAt(index)) break;
            index++;
        }
        if(index==0)
          System.out.println(""+s+ " and "+s2+ " have no common prefix");
        else
          System.out.println(large.substring(0,index));
    }
}

Edit:编辑:

  1. I find the larger of the strings and choose it to be the outer string to loop throught我找到较大的字符串并选择它作为循环通过的外部字符串
  2. toCharArray() converts the string into characters so you can loop through each characters in the string using Java's foreach (For more click [1] ) toCharArray()将字符串转换为字符,因此您可以使用 Java 的 foreach 循环遍历字符串中的每个字符(有关更多信息,请单击[1]
  3. Inside the loop you should exit on two conditions在循环内,您应该在两个条件下退出
    • End of the string (I use length to find if I reach end of smaller string)字符串的结尾(我使用长度来查找是否到达较小字符串的结尾)
    • no more matching characters between two strings两个字符串之间不再有匹配的字符
  4. you increment the index until you break out in one of the above conditions您增加索引,直到您在上述条件之一中突破
  5. By the time you break out of the for loop, index will contain the last index where both string are continuously equal.当您跳出 for 循环时, index将包含两个字符串连续相等的最后一个索引。
  6. If index = 0. just say no matches else print characters from 0 until index如果 index = 0. 只说不匹配其他打印字符从 0 到index
    public static String LcpFinder (String s1 , String s2){

    if (s1 == null || s2 == null){
        throw new IllegalArgumentException();
    }

    int minLength = 0;

    if (s1.length() < s2.length()){
        minLength = s1.length();
    }
    else{
        minLength = s2.length();
    }

    for (int i = 0 ; i < minLength ; i++){

        if(s1.charAt(i) == s2.charAt(i)){
            continue;
        }
        else{
            return s1.substring(0,i);
        }           
    }
    return s1.substring(0,minLength); 
}

str1 = input().lower() str2 = input().lower() str1 = input().lower() str2 = input().lower()

for i in range(min(len(str1),len(str2))): if str1[i]:= str2[i]: break for i in range(min(len(str1),len(str2))): 如果 str1[i]:= str2[i]: break

if i == 0: print(-2) else: print(str1[:i])如果我 == 0: 打印(-2) 否则: 打印(str1[:i])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM