File tree Expand file tree Collapse file tree 2 files changed +41
-6
lines changed
Problems/#14 - Longest Common Prefix - Easy Expand file tree Collapse file tree 2 files changed +41
-6
lines changed Original file line number Diff line number Diff line change 1
- # Problem: Longest Common Prefix
2
- ## Language: C++
1
+ # Leetcode Problem #14 : Longest Common Prefix (Easy)
2
+
3
+ ## Problem
4
+
5
+ Given an array of strings ` strs ` , return the ** longest common prefix** string amongst them.
6
+ If there is no common prefix, return an ** empty string** .
3
7
4
8
---
5
9
6
- 1 . Start with the first string as the prefix.
7
- 2 . For each string in the array:
8
- - Reduce the prefix by comparing it with the current string.
9
- - Stop early if prefix becomes empty.
10
+ ## Approach
11
+
12
+ - Start with the first string as the ** initial prefix** .
13
+ - Compare it with the next string:
14
+ - If the current string doesn't start with the prefix, ** trim the prefix** by one character from the end.
15
+ - Repeat until it matches or becomes an empty string.
16
+ - Continue this for all strings in the list.
10
17
11
18
---
12
19
13
20
14
21
22
+
Original file line number Diff line number Diff line change
1
+ // LeetCode #14 - Longest Common Prefix
2
+ // Language: C++
3
+
4
+ #include < string>
5
+ #include < vector>
6
+
7
+ using namespace std ;
8
+
9
+ class Solution {
10
+ public:
11
+ string longestCommonPrefix (vector<string>& strs) {
12
+ if (strs.empty ()) return " " ;
13
+
14
+ string prefix = strs[0 ];
15
+
16
+ for (int i = 1 ; i < strs.size (); ++i) {
17
+ int j = 0 ;
18
+ while (j < prefix.size () && j < strs[i].size () && prefix[j] == strs[i][j])
19
+ ++j;
20
+ prefix = prefix.substr (0 , j);
21
+ if (prefix.empty ()) return " " ;
22
+ }
23
+
24
+ return prefix;
25
+ }
26
+ };
27
+
You can’t perform that action at this time.
0 commit comments