File tree Expand file tree Collapse file tree 2 files changed +46
-1
lines changed Expand file tree Collapse file tree 2 files changed +46
-1
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ Longest Common Prefix
3
+ =====================
4
+
5
+ Write a function to find the longest common prefix string amongst an array of strings.
6
+
7
+ If there is no common prefix, return an empty string "".
8
+
9
+ Example 1:
10
+ Input: strs = ["flower","flow","flight"]
11
+ Output: "fl"
12
+
13
+ Example 2:
14
+ Input: strs = ["dog","racecar","car"]
15
+ Output: ""
16
+ Explanation: There is no common prefix among the input strings.
17
+
18
+ Constraints:
19
+ 1 <= strs.length <= 200
20
+ 0 <= strs[i].length <= 200
21
+ strs[i] consists of only lower-case English letters.
22
+ */
23
+
24
+ class Solution
25
+ {
26
+ public:
27
+ string longestCommonPrefix (vector<string> &strs)
28
+ {
29
+ string ans;
30
+ int minLen = INT_MAX;
31
+ for (auto &i : strs)
32
+ minLen = min (minLen, (int )i.size ());
33
+ for (int i = 0 ; i < minLen; ++i)
34
+ {
35
+ int ch = strs[0 ][i];
36
+ for (int j = 1 ; j < strs.size (); ++j)
37
+ {
38
+ if (strs[j][i] != ch)
39
+ return ans;
40
+ }
41
+ ans += ch;
42
+ }
43
+ return ans;
44
+ }
45
+ };
Original file line number Diff line number Diff line change 138
138
- [ Integer to Roman] ( https://leetcode.com/problems/integer-to-roman/ ) - [ Cpp Soultion] ( ./Day-15/Integer%20to%20Roman.cpp )
139
139
- [ Implement strStr] ( https://leetcode.com/problems/implement-strstr/ ) - [ Cpp Soultion] ( ./Day-15/Implement%20strStr.cpp )
140
140
- [ String to Integer] ( https://leetcode.com/problems/string-to-integer-atoi/ ) - [ Cpp Soultion] ( ./Day-15/String%20to%20Integer.cpp )
141
- - [ ] ( ) - [ Cpp Soultion] ( ./Day-15/.cpp )
141
+ - [ Longest Common Prefix ] ( https://leetcode.com/problems/longest-common-prefix/ ) - [ Cpp Soultion] ( ./Day-15/Longest%20Common%20Prefix .cpp )
142
142
- [ ] ( ) - [ Cpp Soultion] ( ./Day-15/.cpp )
143
143
144
144
###
You can’t perform that action at this time.
0 commit comments