Problem
Given a string S, return the "reversed" string where all characters that are not a letter stay in the same place, and all letters reverse their positions.
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!"
Note:
S.length <= 100 33 <= S[i].ASCIIcode <= 122 S doesn"t contain or "Solution
class Solution { public String reverseOnlyLetters(String S) { char[] str = S.toCharArray(); int i = 0, j = str.length-1; while (i < j) { while (i < j && !Character.isLetter(str[i])) i++; while (i < j && !Character.isLetter(str[j])) j--; swap(str, i++, j--); } StringBuilder sb = new StringBuilder(); sb.append(str); return sb.toString(); } private void swap(char[] str, int i, int j) { char temp = str[i]; str[i] = str[j]; str[j] = temp; } }
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/72095.html
摘要:題目鏈接題目分析給定一個包含符號的字符串,僅倒轉字母的出現順序,不改變符號的出現位置。思路先把字符串分成字母和符號兩部分,保留下標。抽離字母數組的鍵和值,對值部分進行倒轉,合并到鍵數組中。最終代碼若覺得本文章對你有用,歡迎用愛發電資助。 D63 917. Reverse Only Letters 題目鏈接 917. Reverse Only Letters 題目分析 給定一個包含符號的...
摘要:復雜度思路用一個每次考慮當前的字符大小和的頂端字符的大小,如果當前字符比較小的話,則可以出頂端的字符,將當前的字符放進中。需要維持了一個判斷當前字符在剩余字符串中的出現次數,考慮能否將這個字符從棧中彈出。 LeetCode[316] Remove Duplicate Letters Given a string which contains only lowercase letter...
摘要:首先要求就是得保證在原來的字符串中存在當前字符的順序,即要保證每次的字符的次數大于。讀字符的過程中,把字符存到里,當發現之前存的字符中比當前字符大而且頻率還大于就可以把那個字符出去。基本思想就是在一定的限制條件下出比當前選擇差的元素。 Remove Duplicate Letters Given a string which contains only lowercase lette...
摘要:一題目描述空格分隔,逐個反轉二題目描述三題目描述當然也可以用的做,不過用雙指針更快。 LeetCode: 557. Reverse Words in a String III 一、LeetCode: 557. Reverse Words in a String III 題目描述 Given a string, you need to reverse the order of chara...
Problem You are given a license key represented as a string S which consists only alphanumeric character and dashes. The string is separated into N+1 groups by N dashes. Given a number K, we would wan...
閱讀 3581·2023-04-26 02:55
閱讀 2849·2021-11-02 14:38
閱讀 4136·2021-10-21 09:39
閱讀 2842·2021-09-27 13:36
閱讀 3943·2021-09-22 15:08
閱讀 2644·2021-09-08 10:42
閱讀 2802·2019-08-29 12:21
閱讀 667·2019-08-29 11:22