File tree Expand file tree Collapse file tree 1 file changed +48
-1
lines changed
Expand file tree Collapse file tree 1 file changed +48
-1
lines changed Original file line number Diff line number Diff line change 44
55Write a function to find the longest common prefix string amongst an array of strings.
66
7- ## 思路
7+ ## 思路一
88
99求最长公共前缀。
1010
@@ -49,5 +49,52 @@ class Solution {
4949}
5050```
5151
52+ ## 思路二
53+
54+ 先找出最短字符串的长度,最长公共前缀的长度不会超过最短字符串的长度。
55+ 采用二分查找的思路逐步确定最长公共前缀。
56+
57+ ## 完整代码
58+
59+ ``` java
60+ class Solution {
61+ public String longestCommonPrefix (String [] strs ) {
62+ if (strs == null || strs. length == 0 ) {
63+ return " " ;
64+ }
65+
66+ int minLen = Integer . MAX_VALUE ;
67+ for (String str : strs) {
68+ if (str. length() < minLen) {
69+ minLen = str. length();
70+ }
71+ }
72+
73+ int low = 1 ;
74+ int high = minLen;
75+ while (low <= high) {
76+ int mid = (low + high) / 2 ;
77+ if (isCommonPrefix(strs, mid)) {
78+ low = mid + 1 ;
79+ } else {
80+ high = mid - 1 ;
81+ }
82+ }
83+
84+ return strs[0 ]. substring(0 , (low + high) / 2 );
85+ }
86+
87+ public boolean isCommonPrefix (String [] strs , int mid ) {
88+ String prefix = strs[0 ]. substring(0 , mid);
89+ for (int i = 1 ; i < strs. length; i++ ) {
90+ if (! strs[i]. startsWith(prefix)) {
91+ return false ;
92+ }
93+ }
94+ return true ;
95+ }
96+ }
97+ ```
98+
5299[ title ] : https://leetcode.com/problems/longest-common-prefix
53100[ src ] : https://github.com/andavid/leetcode-java/blob/master/src/com/andavid/leetcode/_014/Solution.java
You can’t perform that action at this time.
0 commit comments