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

问题描述 投票:5回答:3

我想找到两个字符串的最长公共前缀。有没有办法循环我的最后几个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));  
  }
}

例:

Enter first string: Welcome to c++

Enter second string: Welcome to java

代码应将Welcome作为公共前缀返回。

java string loops if-statement
3个回答
3
投票

试试这个。我想这就是你想要实现的目标。如果这是正确的,我会在稍后补充解释

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));
    }
}

编辑:

  1. 我发现较大的字符串并选择它作为循环的外部字符串
  2. toCharArray()将字符串转换为字符,以便您可以使用Java的foreach遍历字符串中的每个字符(有关click[1]的更多信息)
  3. 在循环内部,您应该在两个条件下退出 字符串的结尾(我使用长度来查找是否到达较小的字符串的末尾) 两个字符串之间不再匹配字符
  4. 你增加索引,直到你在上述条件之一中爆发
  5. 当你退出for循环时,index将包含两个字符串连续相等的最后一个索引。
  6. 如果index = 0.只说不匹配,否则从0开始打印字符直到index

3
投票

也许是这样的:

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;
    }
}

但是关于你的问题的更多细节会很棒。

编辑:这取决于@afrojuju_想要做什么。目前尚不清楚。可以添加一些更多逻辑以实现期望的行为。

编辑2:添加了@JavaBeast指出的字符串长度比较。


0
投票
    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); 
}
© www.soinside.com 2019 - 2024. All rights reserved.