LaiCode 395.Remove Certain Characters

LaiCode 395.Remove Certain Characters

题目

在这里插入图片描述

思路

  1. First we need to change the input string into a character array and put the string t into a Hashset.
  2. Then we need to set two pointers, slow and fast, to traverse the character array. The fast pointer will go through every element in each iteration and to see if the element exists in the set. If it exists in the set, then we set the value of the slow pointer’s elements the same as the fast pointer’s element. And move slow and fast pointer to their next element; If it doesn’t exiest in the set, then we only need to move the fast pointer to its next element and go for another iteration.
  3. When the fast pointer reach the end of the character array, the elements in front of the slow pointer is what we need, and we should construct a new string with these elements and return it.

代码实现

public class Solution {
  public String remove(String input, String t) {
    // Write your solution here
    char[] inputStr = input.toCharArray();
    Set<Character> set = buildSet(t);

    int slow = 0;
    for (int fast = 0; fast < inputStr.length; fast++) {
      if (!set.contains(inputStr[fast])) {
        inputStr[slow++] = inputStr[fast];
      }
    }

    return new String(inputStr, 0, slow);
  }

  private Set<Character> buildSet(String t) {
    Set<Character> set = new HashSet<>();
    for (int i = 0; i < t.length(); i++) {
      set.add(t.charAt(i));
    }
    return set;
  }
}

复杂度分析

这种解法的时间复杂度是O(m + n),其中m代表t的长度,n代表input的长度。
空间复杂度是O(m + n),因为要额外创建一个hashset,大小等同于t的大小;还有一个char array,大小等同于input的长度。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值