字符串理论基础
- C与CPP字符串定义的区别:CPP有string类,不会自动添加\0
- KMP算法:前缀表
string s;
s.size();
s += c;
# compare
s.compare(s1) == 0
s == s1
s.resize(size);
reverse(s.begin(), s.end());
# substr: start i, length n,
# compare string ==
haystack.substr(i, n) == needle
# string to int
int a = stoi(tokens[i])
反转字符串-344
Write a function that reverses a string. The input string is given as an array of characters `s`.
You must do this by modifying the input array [in-place](https://en.wikipedia.org/wiki/In-place_algorithm) with `O(1)` extra memory.
要点:
- 关于交换元素的实现方式
- swap函数
- 常见的交换数值
- 位运算
x ^= y
y ^= x;
x ^= y;
错误:
反转字符串II-541
Given a string `s` and an integer `k`, reverse the first `k` characters for every `2k` characters counting from the start of the string.
If there are fewer than `k` characters left, reverse all of them. If there are less than `2k` but greater than or equal to `k` characters, then reverse the first `k` characters and leave the other as original.
要点:
- 写好循环
错误:
反转字符串里的单词-151
Given an input string `s`, reverse the order of the **words**.
A **word** is defined as a sequence of non-space characters. The **words** in `s` will be separated by at least one space.
Return *a string of the words in reverse order concatenated by a single space.*
**Note** that `s` may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.
要点:
- string里面resize()函数用来修改string的大小
- 双指针法
- 算法:两次reverse
错误:
- remove extra space的最后一个index多加了一次
- string类型的函数参数如需引用需要加& 调用的时候不用取地址
- string类型的reverse函数end为end + 1
使用KMP算法匹配字符串-28
需要重新刷
Given two strings `needle` and `haystack`, return the index of the first occurrence of `needle` in `haystack`, or `-1` if `needle` is not part of `haystack`.
要点:
- KMP算法
错误:
- 前缀表计算
- vector 参数引用:调用时不需要加&
- vector size初始化: resize 或者 构造函数
- 利用双循坏结构,现在内循环里面得到pos
找到重复的子字符串-459
Given a string `s`, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together.
要点:
- KMP算法
错误:
- 判断整除需要先考虑前缀表项为0的情况