Algorithm
No.3 Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
解答:
class Solution {
func lengthOfLongestSubstring(_ s: String) -> Int {
var map = [Character: Int](), i = 0, j = 0, longest = 0
let sChars = Array(s)
while j < sChars.count {
let c = sChars[j]
if let index = map[c] {
// 1.滑动窗口
i = max(i, index)
}
// 2.
longest = max(longest, j - i + 1)
j += 1
// 在j+=1之后在存到map中, 以及在2.处计算的 + 1, 是为了兼容 string长度为1的字符串
map[c] = j
}
return longest
}
}
小记:
为什么在上面代码中 1 处要使用max运算选出最大值, 而不是直接将index
赋值给i
?
答: 直接将index
赋值给i
会导致处理类似abba
这种情况出错.
Review
Swift Playgrounds in Depth(Part Two)
原文: https://www.raywenderlich.com/4345-swift-playgrounds-in-depth
第二部分主要是讲Playground在项目中的应用.
AttributedStrings.xcworkspace
在项目中 直接添加一个playground文件(在Xcode10.1中,选中目录Command+N 新建文件 往下拉就可以找到新建Playground一栏)即可.
添加完就可以直接引用所有包含的框架, 也可以进行进一步的测试.
import UIKit
import BonMot
import TextAttributes
func attributedStringWithBonMot(_ inputString: String) -> NSAttributedString {
let style = StringStyle(
.color(.blue),
.font(UIFont(name: "AmericanTypewriter", size: 24)!)
)
return inputString.styled(with: style)
}
attributedStringWithBonMot("Hellow BonMot")
func attributedStringWithTextAttributes(_ inputString: String) -> NSAttributedString {
let attributes = TextAttributes()
.font(name: "ChalkboardSE-Bold", size: 24)
.foregroundColor(.red)
return NSAttributedString(string: inputString, attributes: attributes)
}
attributedStringWithTextAttributes("Hello TextAttributes")
ConverterApp
在这个项目中, 对文件移动不同target进行了一些实践, 需要注意的是 在目前版本的Xcode(10.1)下, 直接移动普通文件(.swift)到另一个target的目录下, 会直接修改该文件所绑定的target, 但是对.xib文件而言, Xcode不会不会自动修改, 需要我们手动修改
修改完编译, 会提示以下信息:
Could not find a storyboard named 'Temperature' in bundle NSBundle ...
这是因为移动过后的xib文件就不在main bundle
中了, 还需要对之前的引用进行修改
在playground中使用这个viewcontroller
let frameworkBundle = Bundle(identifier: "com.razeware.ConverterKit")
let storyboard = UIStoryboard(name: "Temperature", bundle:
frameworkBundle)
let viewController = storyboard.instantiateInitialViewController()!
// 展示
viewController.view
注意 在playground中 instantiate一个控制器会默认将其设置为 768 * 1024的尺寸
为了解决这个尺寸问题, 直接修改frame
是不起作用的, 我们应该讲live view
直接设置为 viewcontroller
PlaygroundPage.current.liveView = viewController
苹果文档里给出了可以这么操作的缘由
同时, 在xib中选中了什么设备/机型 此处就会显示对应的尺寸.
Tips
页内锚点链接实现:
[title](#41)
<h3 id="41">title</h3>
轻轻的我走了, 正如我轻轻的来; 我轻轻的招手, 作别西天的云彩。
如果目标是标题类型(#前缀), 还可以直接使用
[描述](#标题内容)来直接跳转.
试一下:
跳转到Algorithm