替换空格

请实现一个函数,把字符串 s 中的每个空格替换成”%20”。

示例 1:

  1. 输入:s = "We are happy."
  2. 输出:"We%20are%20happy."


限制:0 <= s 的长度 <= 10000

题解
使用 String 的 replace 方法或者遍历读取空格替换。

  • 时间和空间复杂度均为 O(n)

    public class ReplaceSpace {
      public static void main(String[] args) {
          System.out.println(replaceSpace("jlksdjlsdfj dsjklsdj sdj"));
      }
    
      public static String replaceSpace(String s) {
          char[] ch = new char[s.length() * 3];
          int size = 0;
          for (int i = 0; i < s.length(); i++) {
              char c = s.charAt(i); // 获取当前字符
              if (c == ' ') {
                  ch[size++] = '%';
                  ch[size++] = '2';
                  ch[size++] = '0';
              } else {
                  ch[size++] = c;
              }
          }
          return new String(ch, 0, size);
      }
    }
    

    连续字符

    给你一个字符串 s ,字符串的「能量」定义为:只包含一种字符的最长非空子字符串的长度。
    示例:

    输入:s = "abbcccddddeeeeedcba"
    输出:5
    解释:子字符串 "eeeee" 长度为 5 ,只包含字符 'e' 。
    

    题解

  1. 只遍历一遍,初始化当前字符出现次数为 1。
  2. 从 s[1] 开始,如果 s[i]=s[i-1],则将 cnt+1,否则将 cnt 重新置为 1。
  3. 输出 cnt 的最大值。
  • 时间复杂度:O(n)O(n),其中 nn 是字符串 ss 的长度。遍历一次 ss 的时间复杂度为 O(n)O(n)。
  • 空间复杂度:O(1)O(1)。我们只需要常数的空间保存若干变量。

    public class MaxPower {
      public static void main(String[] args) {
          System.out.println(maxPower("abbcccddddeeeeedcba"));
      }
    
      public static int maxPower(String s) {
          int cnt = 1;
          int ans = 1; // 要返回的结果个数
          for (int i = 1; i < s.length(); i++) {
              if (s.charAt(i) == s.charAt(i-1)) {
                  cnt++;
                  ans = Math.max(cnt, ans);
              } else {
                  cnt = 1;
              }
          }
          return ans;
      }
    }
    

    第一个只出现一次的字符

    在字符串 s 中找出第一个只出现一次的字符。如果没有,返回一个单空格。 s 只包含小写字母。 ```shell 输入:s = “abaccdeff” 输出:’b’

输入:s = “” 输出:’ ‘

题解:map 集合
```java
public static char firstUniqChar(String s) {
    Map<Character, Integer> map = new LinkedHashMap<>();
    for (int i = 0; i < s.length(); i++) {
        char ch = s.charAt(i);
        map.put(ch, map.getOrDefault(ch, 0) + 1);
    }
    for (int i = 0; i < s.length(); i++) {
        if (map.get(s.charAt(i)) == 1) {
            return s.charAt(i);
        }
    }
    return ' ';
}