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; } }
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://systransis.cn/yun/72095.html
摘要:題目鏈接題目分析給定一個包含符號的字符串,僅倒轉(zhuǎn)字母的出現(xiàn)順序,不改變符號的出現(xiàn)位置。思路先把字符串分成字母和符號兩部分,保留下標(biāo)。抽離字母數(shù)組的鍵和值,對值部分進(jìn)行倒轉(zhuǎn),合并到鍵數(shù)組中。最終代碼若覺得本文章對你有用,歡迎用愛發(fā)電資助。 D63 917. Reverse Only Letters 題目鏈接 917. Reverse Only Letters 題目分析 給定一個包含符號的...
摘要:復(fù)雜度思路用一個每次考慮當(dāng)前的字符大小和的頂端字符的大小,如果當(dāng)前字符比較小的話,則可以出頂端的字符,將當(dāng)前的字符放進(jìn)中。需要維持了一個判斷當(dāng)前字符在剩余字符串中的出現(xiàn)次數(shù),考慮能否將這個字符從棧中彈出。 LeetCode[316] Remove Duplicate Letters Given a string which contains only lowercase letter...
摘要:首先要求就是得保證在原來的字符串中存在當(dāng)前字符的順序,即要保證每次的字符的次數(shù)大于。讀字符的過程中,把字符存到里,當(dāng)發(fā)現(xiàn)之前存的字符中比當(dāng)前字符大而且頻率還大于就可以把那個字符出去?;舅枷刖褪窃谝欢ǖ南拗茥l件下出比當(dāng)前選擇差的元素。 Remove Duplicate Letters Given a string which contains only lowercase lette...
摘要:一題目描述空格分隔,逐個反轉(zhuǎn)二題目描述三題目描述當(dāng)然也可以用的做,不過用雙指針更快。 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...
閱讀 3599·2023-04-26 02:55
閱讀 2867·2021-11-02 14:38
閱讀 4146·2021-10-21 09:39
閱讀 2856·2021-09-27 13:36
閱讀 3967·2021-09-22 15:08
閱讀 2657·2021-09-08 10:42
閱讀 2811·2019-08-29 12:21
閱讀 678·2019-08-29 11:22