leetcode -- 344、345

344. reverse string

Write a function that reverses a string. The input string is given as an array of characters char[].

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

You may assume all the characters consist of printable ascii characters.

Example 1:

Input: [“h”,“e”,“l”,“l”,“o”]
Output: [“o”,“l”,“l”,“e”,“h”]

Example 2:

Input: [“H”,“a”,“n”,“n”,“a”,“h”]
Output: [“h”,“a”,“n”,“n”,“a”,“H”]

Problem Description

Solution Method

void reverseString(char* s, int sSize)
{
    char temp;
    for (int i = 0; i < sSize/2; i ++)
    {
        temp = s[i];
        s[i] = s[sSize-i-1];
        s[sSize-1-i] = temp;
    }
}

在这里插入图片描述

345.Reverse Vowels of a String

Problem Description

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”.

Solution Method

bool isVowel(int c)
{
    /*
    int vowel[10] = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'};
    for (int i = 0; i < 10; i ++)
    {
        if (c == vowel[i])
            return true;
    }
    */
    // 按下面这么写可以缩短运行时间
    if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U')
        return true;
    return false;
}
char * reverseVowels(char * s)
{
    int len = strlen(s);
    printf("len = %d\n", len);
    int l = 0, r = len-1;
    while (l < r)
    {
        if (isVowel(s[l]) == true && isVowel(s[r]) == true)
        {
            char temp;
            temp = s[l];
            s[l] = s[r];
            s[r] = temp;
            l ++, r--;
        }
        else if (isVowel(s[l]) == true && isVowel(s[r]) == false)
            r --;
        else if (isVowel(s[l]) == false && isVowel(s[r]) == true)
            l ++;
        else if (isVowel(s[l]) == false && isVowel(s[r]) == false)
        {l ++; r --;}
    }
    return s;
}

在这里插入图片描述

发布了184 篇原创文章 · 获赞 253 · 访问量 34万+

猜你喜欢

转载自blog.csdn.net/williamgavin/article/details/104605602