--- title: 'LeetCode 917. Reverse Only Letters' disqus: hackmd --- # LeetCode 917. Reverse Only Letters ## Description Given a string s, reverse the string according to the following rules: All the characters that are not English letters remain in the same position. All the English letters (lowercase or uppercase) should be reversed. Return s after reversing it. ## Example Input: s = "ab-cd" Output: "dc-ba" Input: s = "a-bC-dEf-ghIj" Output: "j-Ih-gfE-dCba" ## Constraints 1 <= s.length <= 100 s consists of characters with ASCII values in the range [33, 122]. s does not contain '\"' or '\\'. ## Answer 此題只轉英文字,所以先抓頭尾,設while(head<tail),然後用while將非英文的字元跳過,用^*^head!='\0'和S < tail當邊界來考慮全跳過的情況,然後再次檢查head<tail,確認之後才反轉。 ```Cin= //2021_11_18 char * reverseOnlyLetters(char * S) { int len = strlen(S); char *head = S, *tail = S + len - 1, temp = '\0'; while(head < tail){ while(*head != '\0' && (*head < 'A' || (*head > 'Z' && *head < 'a') || *head > 'z')){head++;} while(S < tail && (*tail < 'A' || (*tail > 'Z' && *tail < 'a') || *tail > 'z')){tail--;} if(head < tail){ temp = *head; *head = *tail; *tail = temp; head++; tail--; } } return S; } ``` ## Link https://leetcode.com/problems/reverse-only-letters/ ###### tags: `Leetcode`