345. 反转字符串中的元音字母(Swift&C)
2019-06-24 本文已影响0人
entre_los_dos
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-vowels-of-a-string
题目
编写一个函数,以字符串作为输入,反转该字符串中的元音字母。
示例 1:
输入: "hello"
输出: "holle"
示例 2:
输入: "leetcode"
输出: "leotcede"
说明:
元音字母不包含字母"y"。
找出元音字母,只对元音字母反转,其它位置的字母保持不变
方法1-Swift遍历字符串,一个从0开始数,一个从s.count开始数。记住index,交换两个值。
class Solution {
func reverseVowels(_ s: String) -> String {
//将元音字母反转。一个从0开始数,一个从s.count开始数。记住index,交换两个值。
// helloa == halloe
var s = s
var i = 0
var j = s.count-1
while i<j {
//从开始后移i个
var sIndex_i = s.index(s.startIndex, offsetBy: i)
var sIndex_j = s.index(s.startIndex, offsetBy: j)
var str_i = ""
var str_j = ""
//找出从前数第一个是元音的
while (isShoudReplace(string: String(s[sIndex_i])) == false && i<j) {
i += 1
sIndex_i = s.index(s.startIndex, offsetBy: i)
}
while (isShoudReplace(string: String(s[sIndex_j])) == false && i<j) {
j -= 1
sIndex_j = s.index(s.startIndex, offsetBy: j)
}
if i<j {
str_i = String(s[sIndex_i])
str_j = String(s[sIndex_j])
s = s.replacingCharacters(in: sIndex_i...sIndex_i, with: str_j)
s = s.replacingCharacters(in: sIndex_j...sIndex_j, with: str_i)
i += 1
j -= 1
}
}
return s
}
func isShoudReplace(string:String) -> Bool {
if (string == "a" ||
string == "e" ||
string == "i" ||
string == "o" ||
string == "u" ||
string == "A" ||
string == "E" ||
string == "I" ||
string == "O" ||
string == "U") {
return true
}
return false
}
}
超时。所以思路不变,我又用C语言提了一次
方法2-C
int isShouldReplace(char a) {
if (a == 'a' ||
a == 'e' ||
a == 'i' ||
a == 'o' ||
a == 'u' ||
a == 'A' ||
a == 'E' ||
a == 'I' ||
a == 'O' ||
a == 'U') {
return 1;
}
return 0;
}
char * reverseVowels(char * s){
//一个从开始数,一个从最后开始数。交换两个index
int start = 0;
int end = strlen(s)-1;
while (start < end) {
char s_start = s[start];
char s_end = s[end];
while (isShouldReplace(s[start]) == 0 && start<end) {
start ++;
s_start = s[start];
}
while (isShouldReplace(s[end]) == 0 && start<end) {
end --;
s_end = s[end];
}
if (start < end) {
char a = s[start];
s[start] = s[end];
s[end] = a;
start ++;
end --;
}
}
return s;
}
很快。
image.png
最后
用swift超时,我不知道还有没有什么别的办法。。C写的很不熟练~我提的这个,在xcode上跑不动,xcode代码如下,但是leetcode上跑不动。
int isShouldReplace(char a) {
char *words = {"a","e","i","o","u","A","E","I","O","U"};
for (int i=0; i<10; i++) {
if (words[i] == a) {
return 1;
}
}
return 0;
}
char * reverseVowels(char * s){
//一个从开始数,一个从最后开始数。交换两个index
int start = 0;
int end = strlen(s)-1;
char sNew[end];
strcpy(sNew,s);
while (start < end) {
char s_start = s[start];
char s_end = s[end];
while (isShouldReplace(s[start]) == 0 && start<end) {
start ++;
s_start = s[start];
}
while (isShouldReplace(s[end]) == 0 && start<end) {
end --;
s_end = s[end];
}
if (start < end) {
sNew[start] = s_end;
sNew[end] = s_start;
start ++;
end --;
}
}
return &sNew;
}