Skip to content

Commit 832c479

Browse files
committed
165.比较版本号,双指针,字符串分割
1 parent 2e84300 commit 832c479

File tree

3 files changed

+69
-1
lines changed

3 files changed

+69
-1
lines changed

leetcode_Java/DoneTitle.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,7 @@
8484
152. 乘积最大子数组
8585
155. 最小栈
8686
160. 相交链表
87+
165. 比较版本号
8788
169. 多数元素
8889
188. 买卖股票的最佳时机 IV
8990
198. 打家劫舍

leetcode_Java/DoneType.txt

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -193,9 +193,10 @@
193193
8. 字符串转换整数 (atoi)
194194
20. 有效的括号(字符替换,哈希表)
195195
32. 最长有效括号(栈,贪心,计数,动态规划)
196-
43. 字符串相乘
196+
43. 字符串相乘(模拟相乘,位置规律)
197197
76. 最小覆盖子串(双指针,滑动窗口)
198198
151. 颠倒字符串中的单词(分割反转,双指针,双端队列)
199+
165. 比较版本号(双指针,字符串分割)
199200
208. 实现 Trie (前缀树)
200201
394. 字符串解码(栈)
201202
415. 字符串相加(模拟相加)

leetcode_Java/Solution0165.java

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
// 165. 比较版本号
2+
3+
4+
/*
5+
双指针:
6+
1、同时遍历两个字符串,直到全部遍历完
7+
2、双指针分别遍历两个字符串,获取逗号分隔的修订号,将字符转化成数字,比较两个修订号的大小,大于或小于则返回结果1或-1,相同则继续判断下一个修订号,
8+
遍历结束后仍没有返回,说明修订号全部相同,返回0
9+
10+
12.01.33 12.11.33
11+
↑ ↑ ==> 12 = 12
12+
i j
13+
===================================
14+
12.01.33 12.11.33
15+
↑ ↑ ==> 1 < 11
16+
i j
17+
*/
18+
class Solution {
19+
public int compareVersion(String version1, String version2) {
20+
int n1 = version1.length(), n2 = version2.length();
21+
int i = 0, j = 0;
22+
while (i < n1 || j < n2) {
23+
int num1 = 0, num2 = 0;
24+
while (i < n1 && version1.charAt(i) != '.') {
25+
num1 = num1 * 10 + version1.charAt(i++) - '0';
26+
}
27+
while (j < n2 && version2.charAt(j) != '.') {
28+
num2 = num2 * 10 + version2.charAt(j++) - '0';
29+
}
30+
if (num1 > num2) {
31+
return 1;
32+
} else if (num1 < num2) {
33+
return -1;
34+
}
35+
i++;
36+
j++;
37+
}
38+
return 0;
39+
}
40+
}
41+
42+
43+
/*
44+
字符串分割:两个字符串根据'.'分割成字符串数组,同时遍历两个数组,把修订号转化成数字,分别比较修订号
45+
*/
46+
class Solution {
47+
public int compareVersion(String version1, String version2) {
48+
String[] s1 = version1.split("\\.");
49+
String[] s2 = version2.split("\\.");
50+
int n1 = s1.length, n2 = s2.length;
51+
int i = 0, j = 0;
52+
while (i < n1 || j < n2) {
53+
int num1 = 0, num2 = 0;
54+
if (i < n1) {
55+
num1 = Integer.parseInt(s1[i++]);
56+
}
57+
if (j < n2) {
58+
num2 = Integer.parseInt(s2[j++]);
59+
}
60+
if (num1 != num2) {
61+
return num1 > num2 ? 1 : -1;
62+
}
63+
}
64+
return 0;
65+
}
66+
}

0 commit comments

Comments
 (0)