Title Description:
Given a string S , returns the "inverted" string, where characters that are not alphabetic remain in place, and where all letters are reversed.
Example 1:
Input: "AB-CD" output: "Dc-ba"
Example 2:
Input: "A-bc-def-ghij" output: "J-IH-GFE-DCBA"
Example 3:
Input: "test1ng-leet=code-q!" Output: "qedo1ct-eelg=ntse-t!"
Tips:
S.length <= 100
33 <= S[i].ASCIIcode <= 122
Sdoes not contain \ or"
to complete the function:
String Reverseonlyletters (String S)
Description:
1, given a string s, which contains letters (with uppercase and lowercase), and some non-letter symbols.
It is now required to reverse the letters in the string, instead of the alphabetic characters remaining in place without making any changes.
such as A-BCD, the reversal should be D-CBA.
Finally returns the string that was obtained after the reversal.
2, this problem is relatively easy, define two pointers, one from the beginning, one from the back, when the two pointers correspond to the letters, exchange them.
Then the front pointer moves backwards, and the back pointer moves forward, exchanging until two pointers reach the same position.
The code is as follows: (with detailed)
String Reverseonlyletters (String S) { int i=0,s1=s.size (), j=s1-1; while (I<J)//When I and J are not met {if (Isalpha (S[i]))//If I corresponds to the letter {while (j>i)//When I and J are not met { if (Isalpha (S[j]))//If J corresponds to the letter { swap (s[i],s[j]),//i and J correspond to the two letters exchanged with each other j--;//j to the next break;//jump out of the loop , you don't have to find the letter of J. } j--;//If it is not a letter, then keep looking for it } } i++;//after exchange, I go forward and continue looking for the next letter } return S ;//finally returns the "in place" Exchange end of the string }
The above code is measured 0ms,beats 100.00% of CPP submissions.
Leetcode-917-only reverses the letters