一、反转字符串
题目链接:344. 反转字符串
/** * <pre> * 双指针指向头和尾,不断交换并向中间靠拢 * </pre> * * @author <a href="https://github.com/Ken-Chy129">Ken-Chy129</a> * @date 2023/1/9 11:06 */ public class 反转字符串344 { public void reverseString(char[] s) { int len = s.length; char tmp; for (int i=0; i<len/2; i++) { tmp = s[len-i-1]; s[len-i-1] = s[i]; s[i] = tmp; } } }
二、反转字符串II
题目链接:541. 反转字符串 II
/** * <pre> * 每隔k个反转k个,末尾不够k个时全部反转 * </pre> * * @author <a href="https://github.com/Ken-Chy129">Ken-Chy129</a> * @date 2023/1/9 11:16 */ public class 反转字符串II541 { public String reverseStr(String s, int k) { char[] chars = s.toCharArray(); for (int i=0; i<s.length(); i+=2*k) { reserve(chars, i, Math.min(i + k, s.length())); } return new String(chars); } public void reserve(char[] chars, int begin, int end) { int len = end - begin; char tmp; for (int i=0; i<len/2; i++) { tmp = chars[end-i-1]; chars[end-i-1] = chars[begin+i]; chars[begin+i] = tmp; } } }
三、替换空格
题目链接:05. 替换空格
public class 替换空格5 { public String replaceSpace(String s) { StringBuilder sb = new StringBuilder(); for (int i=0; i<s.length(); i++) { if (s.charAt(i) == ' ') { sb.append('%'); sb.append('2'); sb.append('0'); } else { sb.append(s.charAt(i)); } } return sb.toString(); } }
四、翻转字符串里的单词
题目链接:151. 反转字符串中的单词
/** * <pre> * 1.用栈维护 * 2.调用api * </pre> * * @author <a href="https://github.com/Ken-Chy129">Ken-Chy129</a> * @date 2023/1/9 13:57 */ public class 反转字符串中的单词151 { // 用栈维护 public String reverseWords(String s) { int i = 0, len = s.length(); Stack<String> stack = new Stack<>(); while (i<len) { while (i < len && s.charAt(i) == ' ') { i++; } if (i == len) { break; } StringBuilder sb = new StringBuilder(); while (i < len && s.charAt(i) != ' ') { sb.append(s.charAt(i++)); } stack.add(sb.toString()); } StringBuilder res = new StringBuilder(); while (stack.size() > 1) { res.append(stack.pop()); res.append(' '); } res.append(stack.pop()); return res.toString(); } // 调用api public String reverseWords2(String s) { // 除去开头和末尾的空白字符 s = s.trim(); // 正则匹配连续的空白字符作为分隔符分割 List<String> wordList = Arrays.asList(s.split("\\s+")); Collections.reverse(wordList); return String.join(" ", wordList); } }