71. 简化路径/535. TinyURL 的加密与解密
2020-03-20 本文已影响0人
Kevifunau
71. 简化路径
- 相关标签 : 栈 字符串
/*
.
..
... ?
这题 用 memcpy 出现了 bug
memcpy (s1,s2, sizeof(s1))
他是 值比较 S1的长度
strncpy(s1,s2,sizeof(s1))
这个是比较全部 只是对S 有保护
In short:
strcmp compares null-terminated C strings
strncmp compares at most N characters of null-terminated C strings
memcmp compares binary byte buffers of N bytes
所以这题需要用 strncpy
memcmp 把长度固定死了 超了就会heap溢出
/
*/
#include <ctype.h>
#define FILENUM 1000
#define DOT "."
#define DOUDOT ".."
typedef struct {
char *file[FILENUM];
int num;
} File;
char * simplifyPath(char * path){
if (strlen(path) == 0) {
return NULL;
}
int len = strlen(path) + 1;
File *fileList = (File *)malloc(sizeof(File));
memset(fileList, 0, sizeof(File));
fileList->num = -1;
char *delim = "/";
char *token = strtok(path, delim);
while (token != NULL) {
if (strncmp(token, DOT, sizeof(token)) != 0 && strncmp(token, DOUDOT, sizeof(token)) != 0) {
fileList->file[++(fileList->num)] = token;
} else {
if (strncmp(token, DOUDOT, sizeof(token)) == 0) {
if (fileList->num != -1) {
fileList->num--;
}
}
}
token = strtok(NULL, delim);
}
char *res = (char *)malloc(len);
memset(res, 0, len);
if (fileList->num == -1) {
return "/";
}
for (int i = 0; i <= fileList->num; i++) {
sprintf(res + strlen(res), "/%s", fileList->file[i]);
}
return res;
}
535. TinyURL 的加密与解密
/*
维护一个哈希表 C 不行 C 不能有全局变量 !
只能用 异或
*/
// #define PREFIX "http://tinyurl.com/"
// #define HMSIZE 10000
// #define STRLEN 100
// char *hm[HMSIZE];
// int hmIdx = 0;
// /** Encodes a URL to a shortened URL. */
// char* encode(char* longUrl) {
// hmIdx++;
// char *res = (char *)malloc(sizeof(char) * STRLEN);
// memset(res, 0, STRLEN);
// memcpy(res, PREFIX, strlen(PREFIX) + 1); // include '\0'
// sprintf(res + strlen(res), "$%x$", hmIdx);
// hm[hmIdx] = longUrl;
// return res;
// }
// /** Decodes a shortened URL to its original URL. */
// char* decode(char* shortUrl) {
// char *delim = "$";
// char *ptr = strtok(shortUrl, delim);
// ptr = strtok(NULL, delim);
// int hmIdx = atoi(ptr);
// return hm[hmIdx];
// }
#define ENCRYPTION 0xAB
/** Encodes a URL to a shortened URL. */
char* encode(char* longUrl) {
for (int i = 0; i < strlen(longUrl); i++) {
longUrl[i] ^= ENCRYPTION;
}
// printf("%s\n", longUrl);
return longUrl;
}
/** Decodes a shortened URL to its original URL. */
char* decode(char* shortUrl) {
for (int i = 0; i < strlen(shortUrl); i++) {
shortUrl[i] ^= ENCRYPTION;
}
return shortUrl;
}
// Your functions will be called as such:
// char* s = encode(s);
// decode(s);