Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 7b09529

Browse files
Merge pull request youngyangyang04#2800 from zrzhit/master
增加Swift版本 1. 面试题02.07.链表相交 2.右旋字符串
2 parents a299ece + 2ddf04f commit 7b09529

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

‎problems/kamacoder/0055.右旋字符串.md‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -350,7 +350,29 @@ function reverseStr(s, start, end) {
350350

351351

352352
### Swift:
353+
```swift
354+
func rotateWords(_ s: String, _ k: Int) -> String {
355+
var chars = Array(s)
356+
// 先反转整体
357+
reverseWords(&chars, start: 0, end: s.count - 1)
358+
// 反转前半段
359+
reverseWords(&chars, start: 0, end: k - 1)
360+
// 反转后半段
361+
reverseWords(&chars, start: k, end: s.count - 1)
362+
return String(chars)
363+
}
353364

365+
// 反转start...end 的字符数组
366+
func reverseWords(_ chars: inout [Character], start: Int, end: Int) {
367+
var left = start
368+
var right = end
369+
while left < right, right < chars.count {
370+
(chars[left], chars[right]) = (chars[right], chars[left])
371+
left += 1
372+
right -= 1
373+
}
374+
}
375+
```
354376

355377

356378
### PHP:

‎problems/面试题02.07.链表相交.md‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -535,6 +535,45 @@ public ListNode GetIntersectionNode(ListNode headA, ListNode headB)
535535
}
536536
```
537537

538+
### Swift:
539+
```swift
540+
func getIntersectionNode(_ headA: ListNode?, _ headB: ListNode?) -> ListNode? {
541+
var lenA = 0
542+
var lenB = 0
543+
var nodeA = headA
544+
var nodeB = headB
545+
// 计算链表A和链表B的长度
546+
while nodeA != nil {
547+
lenA += 1
548+
nodeA = nodeA?.next
549+
}
550+
while nodeB != nil {
551+
lenB += 1
552+
nodeB = nodeB?.next
553+
}
554+
// 重置指针
555+
nodeA = headA
556+
nodeB = headB
557+
// 如果链表A更长,让它先走lenA-lenB步
558+
if lenA > lenB {
559+
for _ in 0..<(lenA - lenB) {
560+
nodeA = nodeA?.next
561+
}
562+
} else if lenB > lenA {
563+
// 如果链表B更长,让它先走lenB-lenA步
564+
for _ in 0..<(lenB - lenA) {
565+
nodeB = nodeB?.next
566+
}
567+
}
568+
// 同时遍历两个链表,寻找交点
569+
while nodeA !== nodeB {
570+
nodeA = nodeA?.next
571+
nodeB = nodeB?.next
572+
}
573+
return nodeA
574+
}
575+
```
576+
538577

539578
<p align="center">
540579
<a href="https://programmercarl.com/other/kstar.html" target="_blank">

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /