File tree Expand file tree Collapse file tree 3 files changed +62
-0
lines changed
Expand file tree Collapse file tree 3 files changed +62
-0
lines changed Original file line number Diff line number Diff line change 668. 字符串转换整数 (atoi)
7710. 正则表达式匹配
8811. 盛最多水的容器
9+ 14. 最长公共前缀
91015. 三数之和
101117. 电话号码的字母组合
111219. 删除链表的倒数第 N 个结点
Original file line number Diff line number Diff line change 191191八、字符串
1921923. 无重复字符的最长子串(滑动窗口)
1931938. 字符串转换整数 (atoi)
194+ 14. 最长公共前缀(横向比较,纵向比较)
19419520. 有效的括号(字符替换,哈希表)
19519632. 最长有效括号(栈,贪心,计数,动态规划)
19619743. 字符串相乘(模拟相乘,位置规律)
Original file line number Diff line number Diff line change 1+ // 14. 最长公共前缀
2+
3+
4+ /*
5+ 横向比较:
6+ 1、当字符串数组长度为 0 时则公共前缀为空,直接返回
7+ 2、令第一个字符串为最长公共前缀,进行初始化
8+ 3、第一个for循环遍历数组,第二个while循环遍历字符
9+ 即横向比较,遍历后面的字符串,依次将其与第一个字符串进行比较,两两找出公共前缀并截取第一个字符串,最终结果即为最长公共前缀
10+ 4、如果查找过程第一个字符串截取后为空,则后面的字符串不用判断了,直接返回
11+ */
12+ class Solution {
13+ public String longestCommonPrefix (String [] strs ) {
14+ int n = strs .length ;
15+ if (n == 0 ) {
16+ return "" ;
17+ }
18+ String firstStr = strs [0 ];
19+ for (int i = 1 ; i < n ; i ++) {
20+ int j = 0 ;
21+ String curStr = strs [i ];
22+ while (j < firstStr .length () && j < curStr .length () && firstStr .charAt (j ) == curStr .charAt (j )) {
23+ j ++;
24+ }
25+ firstStr = firstStr .substring (0 , j );
26+ if (firstStr .equals ("" )) {
27+ return firstStr ;
28+ }
29+ }
30+ return firstStr ;
31+ }
32+ }
33+
34+
35+ /*
36+ 纵向比较:
37+ 1、当字符串数组长度为 0 时则公共前缀为空,直接返回
38+ 2、第一个for循环遍历字符,第二个for循环遍历数组。即纵向比较同一位置上 其他字符串的字符 是否与 第一个字符串的字符 相同
39+ 相同则继续往后判断,遍历结束表示全部相同,返回第一个字符串
40+ 越界或不同则结束判断,然后第一个字符串截取出最长公共前缀
41+ */
42+ class Solution {
43+ public String longestCommonPrefix (String [] strs ) {
44+ int n = strs .length ;
45+ if (n == 0 ) {
46+ return "" ;
47+ }
48+ String firstStr = strs [0 ];
49+ int m = firstStr .length ();
50+ for (int i = 0 ; i < m ; i ++) {
51+ for (int j = 1 ; j < n ; j ++) {
52+ String curStr = strs [j ];
53+ if (i == curStr .length () || curStr .charAt (i ) != firstStr .charAt (i )) {
54+ return firstStr .substring (0 , i );
55+ }
56+ }
57+ }
58+ return firstStr ;
59+ }
60+ }
You can’t perform that action at this time.
0 commit comments