C/C++学习路线 (点击解锁)(●’◡’●) |
---|
❤️C语言 |
❤️初阶数据结构与算法 |
❤️C++ |
❤️高阶数据结构 |
❤️Linux系统编程与网络编程 |
389. 找不同
给定两个字符串 s 和 t ,它们只包含小写字母。
字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。
请找出在 t 中被添加的字母。
-
示例 1:
输入:s = “abcd”, t = “abcde”
输出:“e”
解释:‘e’ 是那个被添加的字母。 -
示例 2:
输入:s = “”, t = “y”
输出:“y”
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/find-the-difference
- 该题我们可以巧妙运用ASCLL码值转换来求出那个被添加的字母
- 因为只添加了一个,所以我们可以把两个字符串的自己所有字符以ascll码表转换为对应ascll值并相加,相减 +’0‘ 便是添加的那个字符
代码如下:
char findTheDifference(char * s, char * t){
int len_t = strlen(t);
int len_s = strlen(s);
int i = 0;
int sum1 = 0;
int sum2 = 0;
for (i = 0; i < len_t; i++)
{
sum1 += *(t + i) - '0';
}
for (i = 0; i < len_s; i++)
{
sum2 += *(s + i) - '0';
}
return ((sum1 - sum2) + '0');
}
434. 字符串中的单词数
统计字符串中的单词个数,这里的单词指的是连续的不是空格的字符。
请注意,你可以假定字符串里不包括任何不可打印的字符。
-
示例:
输入: “Hello, my name is John”
输出: 5
解释: 这里的单词是指连续的不是空格的字符,所以 “Hello,” 算作 1 个单词。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/number-of-segments-in-a-string
- 如果该字符不是空格且不是’\0‘,且前面的字符为 ’ ‘,那么计数一次,记数的是以这个字符开头的单词。
int my_strlen(char* s)
{
int count = 0;
while (*s++ != '\0')
{
count++;
}
return count;
}
int countSegments(char * s){
char* p = s;
int count = 0;
if (*s == '\0') // 如果输入为 ”“ 直接返回0;
{
return 0;
}
else
{
if (*s != ' ') // 如果第一个字符不是’ ‘直接计数一次,这一次计数的是第一个单词
{
count++;
}
for (int i = 1; i < my_strlen(s); i++) // 从1开始包含了第一个字符为’ ‘的情况
{
if (*(p + i) != ' ' && *(p + i - 1) == ' ')
{
count++;
}
}
}
return count;
}
1528. 重新排列字符串
给你一个字符串 s 和一个 长度相同 的整数数组 indices 。
请你重新排列字符串 s ,其中第 i 个字符需要移动到 indices[i] 指示的位置。
返回重新排列后的字符串。
- 示例 1:
输入:s = "codeleet", indices = [4,5,6,7,0,2,1,3]
输出:"leetcode"
解释:如图所示,"codeleet" 重新排列后变为 "leetcode" 。
-
示例 2:
输入:s = “abc”, indices = [0,1,2]
输出:“abc”
解释:重新排列后,每个字符都还留在原来的位置上。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/shuffle-string
- 如下代码,当 i = 0 时,只要 indices[i] != i,就将 indices[i] 对应的值以及s[i]对应的字符与此时下标为indices[i]的值或字符交换,直到 indices[i] = i 为止 。
char * restoreString(char * s, int* indices, int indicesSize){
int len = strlen(s);
for (int i = 0 ; i < indicesSize; i++)
{
while (indices[i] != i) // 直到整型数组当前的下标等于当前对应下标的值为止
{
int j = indices[i];
char tmp1 = s[i];
s[i] = s[j];
s[j] = tmp1;
int tmp2 = indices[i];
indices[i] = indices[j];
indices[j] = tmp2;
}
}
return s;
}