用C语言编写给定一个字符串 s ,请你找出其中不含有重复字符的最长子串的长度。
时间: 2024-03-01 07:45:18 浏览: 50
给定一个字符串 s,要找出其中不含有重复字符的最长子串的长度,可以使用双指针维护一个滑动窗口,不断移动右指针,直到遇到重复字符的时候把左指针移到前面的重复字符的下一位。移动指针过程中,记录窗口长度的最大值即为答案。具体实现可以使用一个哈希表来存储每个字符最后一次出现的位置,如果当前字符已经在哈希表中出现过并且它的位置在左指针的右边,就更新左指针的位置。最后返回最大的窗口长度即可。
C语言代码如下:
```c
int lengthOfLongestSubstring(char * s){
int len = strlen(s);
int left = 0, res = 0;
int map[128] = {0};
for (int i = 0; i < len; i++) {
if (map[s[i]] > left) {
left = map[s[i]];
}
map[s[i]] = i + 1;
res = fmax(res, i - left + 1);
}
return res;
}
```
相关问题
用C语言队列实现:【问题描述】 给定一个字符串,请你找出其中不含有重复字符的最长子串的长度。 Given a string, Please find out the length of the longest substring that does not contain repeated characters. 提示:相同字符大小写算做两个不同字符,如Aa为2 【输入形式】 字符串的内容 【输出形式】 不含有重复字符的最长子串的长度 【样例输入】 abcabcbb 【样例输出】 3
以下是用C语言队列实现的代码:
```c
#include <stdio.h>
#include <string.h>
#define MAX_QUEUE_SIZE 1000
typedef struct {
char data[MAX_QUEUE_SIZE];
int front;
int rear;
} Queue;
void initQueue(Queue *q) {
q->front = q->rear = 0;
}
int isQueueEmpty(Queue *q) {
return q->front == q->rear;
}
int isQueueFull(Queue *q) {
return (q->rear + 1) % MAX_QUEUE_SIZE == q->front;
}
void enqueue(Queue *q, char c) {
if (isQueueFull(q)) {
fprintf(stderr, "Error: queue is full\n");
return;
}
q->data[q->rear] = c;
q->rear = (q->rear + 1) % MAX_QUEUE_SIZE;
}
char dequeue(Queue *q) {
if (isQueueEmpty(q)) {
fprintf(stderr, "Error: queue is empty\n");
return '\0';
}
char c = q->data[q->front];
q->front = (q->front + 1) % MAX_QUEUE_SIZE;
return c;
}
int maxLengthSubstring(char *s) {
int n = strlen(s);
int maxLen = 0;
Queue q;
initQueue(&q);
for (int i = 0; i < n; i++) {
char c = s[i];
int j;
for (j = q.front; j != q.rear; j = (j + 1) % MAX_QUEUE_SIZE) {
if (q.data[j] == c) {
break;
}
}
if (j != q.rear) {
// found repeated character, dequeue until no repeat
while (!isQueueEmpty(&q) && q.data[q.front] != c) {
dequeue(&q);
}
dequeue(&q);
}
enqueue(&q, c);
int len = q.rear - q.front;
if (len > maxLen) {
maxLen = len;
}
}
return maxLen;
}
int main() {
char s[1000];
scanf("%s", s);
printf("%d\n", maxLengthSubstring(s));
return 0;
}
```
算法思路:
使用队列维护一个滑动窗口,窗口内的字符都是不重复的。遍历字符串,对于每个字符,判断是否在窗口内出现过,如果是则将队列中该字符之前的所有字符出队,直到队列中不含有该字符,然后将该字符入队,更新最长不重复子串的长度。
给定一个字符串,求它的最长回文子串的长度,C语言实现
您好,可以使用 Manacher 算法来求解最长回文子串的长度。
该算法的时间复杂度为 O(n),并且可以在线性时间内找到所有回文子串的起始位置。
下面是 C 语言的实现方法:
```
#include <stdio.h>
#include <string.h>
#define max(a, b) ((a) > (b) ? (a) : (b))
char str[100010];
int p[100010];
int main()
{
scanf("%s", str + 1);
int n = strlen(str + 1);
int mx = 0, id = 0;
for (int i = 1; i <= n; i++)
{
if (mx > i)
p[i] = min(p[(id << 1) - i], mx - i);
else
p[i] = 1;
while (str[i - p[i]] == str[i + p[i]])
p[i]++;
if (p[i] + i > mx)
{
mx = p[i] + i;
id = i;
}
}
int ans = 0;
for (int i = 1; i <= n; i++)
ans = max(ans, p[i] - 1);
printf("%d\n", ans);
return 0;
}
```
希望这对您有帮助!