摘要:,這里要注意循環的是前個元素,不是當前元素在循環條件里前移,新位置的指針在語句前移序數從后向前沒有空格也要把當前位元素移到新的位置
Problem
Write a method to replace all spaces in a string with %20. The string is given in a characters array, you can assume it has enough space for replacement and you are given the true length of the string.
You code should also return the new length of the string after replacement.
ExampleGiven "Mr John Smith", length = 13.
The string after replacement should be "Mr%20John%20Smith".
NoteIf you are using Java or Python,please use characters array instead of string.
ChallengeDo it in-place.
SolutionIt"s a easy problem but you are required to do it in-place.
No StringBuilder.
public class Solution { public int replaceBlank(char[] str, int length) { if (length == 0) return 0; int len = length; //calculate the new length after all the replacements for (int i = 0; i < len; i++) { if (str[i] == " ") { len += 2; } } int j = 1; //這里要注意:循環的是前length-1個元素,不是len-1 for (int i = length - 1; i >= 0; i--) { //當前元素i--在for循環條件里前移,新位置的指針(len - j++)在if-else語句前移 if (str[i] == " ") { //序數從后向前 len-1 len-2 len-3 str[len - j++] = "0"; str[len - j++] = "2"; str[len - j++] = "%"; } //沒有空格也要把當前位元素移到新的位置 else { str[len - j++] = str[i]; } } return len; } }
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://m.specialneedsforspecialkids.com/yun/65507.html
Problem Given a positive integer n and you can do operations as follow: 1.If n is even, replace n with n/2.2.If n is odd, you can replace n with either n + 1 or n - 1. What is the minimum number of re...
摘要:構造數組,是的,是的,是將位的轉換成位的需要的步數。初始化和為到它們各自的距離,然后兩次循環和即可。 Problem Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 s...
摘要:從末位向前遍歷,假設循環開始全是倒序排列,如當第一次出現正序的時候,如的和此時從數列末尾向前循環到,找到第一個比大的交換這兩個數,變成倒置第位到末位的數為正序排列這里的是完全倒置的排列,如,即上面循環的情況完全沒有出現, Problem Implement next permutation, which rearranges numbers into the lexicographic...
摘要:把矩陣所有零點的行和列都置零,要求不要額外的空間。對于首行和首列的零點,進行額外的標記即可。這道題我自己做了四遍,下面幾個問題需要格外注意標記首行和首列時,從到遍歷時,若有零點,則首列標記為從到遍歷,若有零點,則首行標記為。 Problem Given a m x n matrix, if an element is 0, set its entire row and column t...
摘要:最長連續遞增遞減子序列,設置正向計數器,后一位增加則計數器加,否則置。反向計數器亦然。每一次比較后將較大值存入。 Problem 最長連續遞增/遞減子序列 Give an integer array,find the longest increasing continuous subsequence in this array.An increasing continuous subs...
閱讀 3390·2022-01-04 14:20
閱讀 3117·2021-09-22 15:08
閱讀 2204·2021-09-03 10:44
閱讀 2321·2019-08-30 15:44
閱讀 1500·2019-08-29 18:40
閱讀 2665·2019-08-29 17:09
閱讀 2993·2019-08-26 13:53
閱讀 3226·2019-08-26 13:37