64,077
社区成员
发帖
与我相关
我的任务
分享
bool isInWords(char ch, char* words){//判断该字符是否在字符串中,该字符大小写不敏感
for(int i = 0; words[i]; ++i){
if(ch == words[i] || ch + 32 == words[i]) return true;
}
return false;
}
char ** findWords(char ** words, int wordsSize, int* returnSize){
char** ret = (char**)malloc(sizeof(char*) * wordsSize);//申请一个二维数组储存答案
for(int i = 0; i < wordsSize; ++i){
ret[i] = (char*)malloc(sizeof(char) * 100);
}
char keyboard[3][11] = {"qwertyuiop","asdfghjkl","zxcvbnm"};//记录键盘上字母的分布情况
int cnt = 0;
for(int i = 0; i < wordsSize; ++i){
int flag, sign = 1;
for(int j = 0; words[i][j]; ++j){
if(j == 0){//记录该行第一个字符出现在键盘第几行
if(isInWords(words[i][j], keyboard[0])){
flag = 0;
}
else if(isInWords(words[i][j], keyboard[1])){
flag = 1;
}
else{
flag = 2;
}
}
else{//判断除第一个字符外的其他字符是否和第一个字符所在行相同
if(!isInWords(words[i][j], keyboard[flag])){
sign = 0;
break;
}
}
}
if(sign){//如果每一个字符都在键盘同一行,将这行加入ret数组中
strcpy(ret[cnt++], words[i]);
}
}
*returnSize = cnt;
return ret;
}
int countCharacters(char ** words, int wordsSize, char * chars){
int ans = 0;
int ch[26] = {0};//使用哈希表记录chars中字母出现情况
for(int i = 0; chars[i]; ++i){
++ch[chars[i] - 'a'];
}
for(int i = 0; i < wordsSize; ++i){
int hash[26];
for(int k = 0; k < 26; ++k){
hash[k] = ch[k];
}//复制哈希表ch到hash中
int flag = 1;
for(int j = 0; words[i][j]; ++j){//一一比较,看chars中的字母能否组合成words[i]
--hash[words[i][j] - 'a'];
if(hash[words[i][j] - 'a'] < 0){
flag = 0;
break;
}
}
if(flag) ans += strlen(words[i]);
}
return ans;
}
尝试了下链栈(但是肯定用数组更好)
typedef struct node{
char data;
struct node* next;
}Node;
typedef struct stack{
Node* head;
int size;
}Stack;
Node* CreatStack(){
Node* head = (Node*)malloc(sizeof(Node));
head->data = '0';
head->next = NULL;
return head;
}
bool isStackVoid(Stack* List){
if(List->size) return false;
else return true;
}
void Push(Stack* List, char ch){
Node* p = (Node*)malloc(sizeof(Node));
p->data = ch;
p->next = List->head->next;
List->head->next = p;
++List->size;
}
void Pop(Stack* List){
if(isStackVoid(List)) return;
Node* q = List->head->next;
List->head->next = q->next;
free(q);
--List->size;
}
char GetTop(Stack* List){
if(isStackVoid(List)) return '0';
return List->head->next->data;
}
char * removeDuplicates(char * s){
//创建栈,维护一个栈顶指针和栈底指针
Stack List;
List.size = 0;
List.head = CreatStack();
//若与栈顶相等则出栈,否则进栈
for(int i = 0; s[i]; ++i){
if(s[i] == GetTop(&List)){
Pop(&List);
}
else{
Push(&List, s[i]);
}
}
s[List.size] = '\0';
for(int i = List.size - 1; i >= 0; --i){
s[i] = GetTop(&List);
Pop(&List);
}
return s;
}
int canBeTypedWords(char * text, char * brokenLetters){
int hash[26] = {0};
int flag = 1;
int ans = 0;
//哈希表记录坏掉的字母
for(int i = 0; brokenLetters[i]; ++i){
hash[brokenLetters[i] - 'a'] = 1;
}
for(int i = 0; text[i]; ++i){
if(i == strlen(text) - 1){//最后一个特殊处理,因为最后没有空格
if(!hash[text[i] - 'a'] && flag) ++ans;
}
else if(text[i] == ' '){//以空格为分割点,根据标记对单词进行判断是否要加入结果
ans += flag;
flag = 1;
}
else if(hash[text[i] - 'a']) flag = 0;//如果中间出现坏掉的字母就将该单词标记
}
return ans;
}