iT邦幫忙

0

【LeetCode with C: A Series of Problem-Solving Techniques】-- Reverse String

  • 分享至 

  • xImage
  •  

Description

  1. Reverse String

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

You must do this by modifying the input array in-place with O(1) extra memory.

Example 1:

Input: s = ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
Example 2:

Input: s = ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]

Constraints:

1 <= s.length <= 105
s[i] is a printable ascii character.

Answer & Explaining

Reverse function

void reverseString(char* s, int sSize) {
    int left = 0;
    int right = sSize - 1;
    while (left < right) { //不斷執行直到相遇
        // Swap the characters at left and right indices
        char temp = s[left];
        s[left++] = s[right];
        s[right--] = temp;
    }
}

Testing

int main() {
    char s1[] = {'h', 'e', 'l', 'l', 'o'};
    int s1Size = sizeof(s1) / sizeof(s1[0]);
    printf("Original: ");
    printArray(s1, s1Size);

    reverseString(s1, s1Size);
    printf("Reversed: ");
    printArray(s1, s1Size);

    char s2[] = {'H', 'a', 'n', 'n', 'a', 'h'};
    int s2Size = sizeof(s2) / sizeof(s2[0]);
    printf("Original: ");
    printArray(s2, s2Size);

    reverseString(s2, s2Size);
    printf("Reversed: ");
    printArray(s2, s2Size);

    return 0;
}

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言