介绍
字符串是以 null 字符为终止的字符数组。 C++ 标准库提供了 string 类型,满足增删改查等一系列操作。
题目
459. 重复的子字符串
给定一个非空的字符串 s ,检查是否可以通过由它的一个子串重复多次构成。
class Solution {
public:
bool repeatedSubstringPattern(string s) {
string t = s + s;
t.erase(t.begin());
t.erase(t.end() - 1);
if (t.find(s) == std::string::npos) return 0;
return 1;
}
};
28. 找出字符串中第一个匹配项的下标
给你两个字符串 haystack
和 needle
,请你在 haystack
字符串中找出 needle
字符串的第一个匹配项的下标(下标从 0
开始)。如果 needle
不是 haystack
的一部分,则返回 -1
。
class Solution {
public:
int strStr(string haystack, string needle) {
if (haystack.size() < needle.size()) return -1;
for (int i = 0; i <= haystack.size() - needle.size(); i++) {
if (haystack[i] == needle[0]) {
int k = i , j = 0;
while (k < haystack.size()) {
if (haystack[k] != needle[j]) break;
if (j == needle.size() - 1) return i;
j++;
k++;
}
}
}
return -1;
}
};
828. 统计子串中的唯一字符
我们定义了一个函数 countUniqueChars(s)
来统计字符串 s 中的唯一字符,并返回唯一字符的个数。
例如:s = "LEETCODE"
,则其中 "L"
, "T"
,"C"
,"O"
,"D"
都是唯一字符,因为它们只出现一次,所以 countUniqueChars(s) = 5
。
本题将会给你一个字符串 s
,我们需要返回 countUniqueChars(t)
的总和,其中 t
是 s
的子字符串。输入用例保证返回值为 32 位整数。
class Solution {
public:
int uniqueLetterString(string s) {
long long ans = 0;
for (char cha = 'A'; cha <= 'Z'; cha++) {
for (int j = 0, left = -1, right = -1; j < s.size(); j++) {
if (s[j] == cha) left = right, right = j;
ans += right - left;
}
}
return ans;
}
};