Merge pull request #2800 from zrzhit/master

增加Swift版本  1. 面试题02.07.链表相交  2.右旋字符串
This commit is contained in:
程序员Carl
2024-11-27 09:17:07 +08:00
committed by GitHub
2 changed files with 61 additions and 0 deletions

View File

@ -350,7 +350,29 @@ function reverseStr(s, start, end) {
### Swift:
```swift
func rotateWords(_ s: String, _ k: Int) -> String {
var chars = Array(s)
// 先反转整体
reverseWords(&chars, start: 0, end: s.count - 1)
// 反转前半段
reverseWords(&chars, start: 0, end: k - 1)
// 反转后半段
reverseWords(&chars, start: k, end: s.count - 1)
return String(chars)
}
// 反转start...end 的字符数组
func reverseWords(_ chars: inout [Character], start: Int, end: Int) {
var left = start
var right = end
while left < right, right < chars.count {
(chars[left], chars[right]) = (chars[right], chars[left])
left += 1
right -= 1
}
}
```
### PHP

View File

@ -535,6 +535,45 @@ public ListNode GetIntersectionNode(ListNode headA, ListNode headB)
}
```
### Swift
```swift
func getIntersectionNode(_ headA: ListNode?, _ headB: ListNode?) -> ListNode? {
var lenA = 0
var lenB = 0
var nodeA = headA
var nodeB = headB
// 计算链表A和链表B的长度
while nodeA != nil {
lenA += 1
nodeA = nodeA?.next
}
while nodeB != nil {
lenB += 1
nodeB = nodeB?.next
}
// 重置指针
nodeA = headA
nodeB = headB
// 如果链表A更长让它先走lenA-lenB步
if lenA > lenB {
for _ in 0..<(lenA - lenB) {
nodeA = nodeA?.next
}
} else if lenB > lenA {
// 如果链表B更长让它先走lenB-lenA步
for _ in 0..<(lenB - lenA) {
nodeB = nodeB?.next
}
}
// 同时遍历两个链表,寻找交点
while nodeA !== nodeB {
nodeA = nodeA?.next
nodeB = nodeB?.next
}
return nodeA
}
```
<p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank">