Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions Java/LargestCommonPrefix.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/* Author : Shuyin Liu
* Problem : To find the longest common prefix string amongst an array of strings, input on command line.
* Explanation : Sample command -- java LongestCommonPrefix apple application appointment
*/
class LongestCommonPrefix {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

Critical: Filename and class name mismatch.

The class is named LongestCommonPrefix but the file is named LargestCommonPrefix.java. In Java, the public class name must exactly match the filename, otherwise the code will not compile.

Rename the file to match the class name:

-Java/LargestCommonPrefix.java
+Java/LongestCommonPrefix.java

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In Java/LargestCommonPrefix.java around line 5, the declared class name
LongestCommonPrefix does not match the filename LargestCommonPrefix.java; update
one to match the other to fix the compilation error — either rename the file to
LongestCommonPrefix.java or rename the class to public class LargestCommonPrefix
(and update any references/imports accordingly) so the public class name exactly
matches the filename.

public static void main(String[] args) {
System.out.print("The common prefix is:");
if (args.length == 0) {
System.out.println("");
return;
}
if (args.length == 1) {
System.out.println(args[0]);
return;
}

String prev = args[0];

for (int i = 1; i < args.length; i++) {
prev = getCommonPrefix(prev, args[i]);
if (prev.isEmpty()) {
System.out.println("");
return;
}
}

System.out.println(prev);
}

private static String getCommonPrefix(String a, String b) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < a.length() && i < b.length(); i++) {
if (a.charAt(i) == b.charAt(i)) {
sb.append(a.charAt(i));
} else {
break;
}
}
return sb.toString();
}
}