-
Notifications
You must be signed in to change notification settings - Fork 2
/
q0345.c
135 lines (130 loc) · 2.59 KB
/
q0345.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
//
// q0345.c
// LeetCode
//
// Created by NowOrNever on 22/10/2019.
// Copyright © 2019 DoubleL. All rights reserved.
//
#include "q0345.h"
#include "../common.h"
//345. Reverse Vowels of a String
//Easy
//426
//808
//
//Favorite
//
//Share
//Write a function that takes a string as input and reverse only the vowels of a string.
//
//Example 1:
//
//Input: "hello"
//Output: "holle"
//Example 2:
//
//Input: "leetcode"
//Output: "leotcede"
//Note:
//The vowels does not include the letter "y".
//
//
//
//Accepted
//169,913
//Submissions
//403,691
bool isVowels(char c){
bool flag = false;
switch (c) {
case 'a':
flag = true;
break;
case 'A':
flag = true;
break;
case 'e':
flag = true;
break;
case 'E':
flag = true;
break;
case 'i':
flag = true;
break;
case 'I':
flag = true;
break;
case 'o':
flag = true;
break;
case 'O':
flag = true;
break;
case 'u':
flag = true;
break;
case 'U':
flag = true;
break;
default:
break;
}
return flag;
}
// why heap-buffer-overflow?
//char * reverseVowels(char * s){
// int len = (int) strlen(s);
// if (len < 1) {
// return s;
// }
// char *p_tail = s + len - 1;
// char *p_head = s;
// char *result = calloc(len, sizeof(char));
// char *p_result = result;
// while (*p_head != '\0') {
// if (isVowels(*p_head)) {
// while (!isVowels(*p_tail)) {
// p_tail--;
// }
// *p_result++ = *p_tail--;
// }else{
// *p_result++ = *p_head;
// }
// p_head++;
// }
// return result;
//}
char * reverseVowels(char * s){
int len = (int) strlen(s);
if (len < 2) {
return s;
}
char *p_tail = s + len - 1;
char *p_head = s;
char temp = ' ';
while (p_head < p_tail) {
bool head_flag = isVowels(*p_head);
bool tail_flag = isVowels(*p_tail);
if (head_flag && tail_flag) {
temp = *p_head;
*p_head = *p_tail;
*p_tail = temp;
}else if (head_flag){
p_head--;
}else if(tail_flag){
p_tail++;
}else{
}
p_head++;
p_tail--;
}
return s;
}
int question345(){
char s[] = "hello";
printf("%s\n",s);
char *result = reverseVowels(s);
printf("%s\n",result);
return 0;
}