Day17——双指针专题
文章目录
- 36.移除元素
- 37.反转字符串
- 38.替换空格
#
36.移除元素
思路:快慢指针,分别设置两个指针,快指针遍历需要的数组,将需要的数组付给slow指向的数组
实现代码:
class Solution {
public int removeElement(int[] nums, int val) {
int slowIndex = 0;
for (int fastindex = 0;fastindex<nums.length;fastindex++){
if(nums[fastindex]!=val){
nums[slowIndex] = nums[fastindex];
slowIndex++;
}
}
return slowIndex;
}
}
37.反转字符串
实现代码:
class Solution {
public void reverseString(char[] s) {
int j = s.length-1;
int i = 0;
while(j>i){
char temp = s[i];
s[i] = s[j];
s[j] = temp;
i++;
j--;
}
}
}
38.替换空格
实现代码:
class Solution {
public String replaceSpace(String s) {
StringBuffer res = new StringBuffer();
for(Character c : s.toCharArray()){
//由字符串转换成字符串数组
if(c == ' ') res.append("%20");
else res.append(c);
}
return res.toString();//由字符串数组转换成字符串
}
}
还没有评论,来说两句吧...