Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit81cff62

Browse files
EASY/src/easy/LongestCommonPrefix.java
1 parentbb2b2e1 commit81cff62

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
packageeasy;
2+
3+
publicclassLongestCommonPrefix {
4+
5+
publicstaticStringlongestCommonPrefix(String[]strs) {
6+
if(strs.length ==0)return"";
7+
8+
inti =0;
9+
Stringprefix ="";
10+
Stringresult ="";
11+
booleanbroken =false;
12+
while(true){
13+
i++;
14+
result =prefix;
15+
if(i >strs[0].length())break;//this will break out the while loop
16+
prefix =strs[0].substring(0,i);
17+
for(Stringword :strs){
18+
if(i >word.length() || !word.startsWith(prefix)) {
19+
broken =true;
20+
break;//this will only break out of the for loop
21+
}
22+
}
23+
if(broken)break;//this will break out the while loop
24+
}
25+
returnresult;
26+
}
27+
28+
publicstaticvoidmain(String...strings){
29+
// String[] strs = new String[]{"a"};
30+
String[]strs =newString[]{"a","b"};
31+
System.out.println(longestCommonPrefix(strs));
32+
}
33+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp