LeetCode | 344. Reverse String, 541. Reverse String II, 剑05. 替换空格,151. Reverse Words in a String,剑58

344. Reverse String

Link: https://leetcode.com/problems/reverse-string/

Description

Write a function that reverses a string. The input string is given as an array of characters s.

You must do this by modifying the input array in-place with O(1) extra memory.

Approach

Two pointers

  • Initialize start points to the first element of s, end points to the last element of s.
  • Swap start and end, then both pointers move towards the middle at the same time.
  • Stop when start and end meet.

Solution

class Solution {
    public void reverseString(char[] s) {
        int left = 0;
        int right = s.length - 1;
        while (left < right) {
            char temp = s[left];
            s[left] = s[right];
            s[right] = temp;
            left++;
            right--;
        }
    }
}

541. Reverse String II

Link: https://leetcode.com/problems/reverse-string-ii/

Description

Given a string s and an integer k, reverse the first k characters for every 2k characters counting from the start of the string.

If there are fewer than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and leave the other as original.

Approach

Two pointers

  • Traverse s:
    • If there are more than k characters left, reverse k elements; else, reverse all of them
    • let i = i + 2k, traverse every 2k characters.

Solution

class Solution {
    public String reverseStr(String s, int k) {
        char[] c = s.toCharArray();
        for (int i = 0; i < c.length; i += 2 * k) {
            if (i + k < c.length) {
                swap(c, i, i + k - 1);
            }
            else {
                swap(c, i, c.length - 1);
            }          
            
        }
        return new String(c);
    }

    private void swap(char[] c, int left, int right) {
        while (left < right) {
            char temp = c[left];
            c[left] = c[right];
            c[right] = temp;
            left++;
            right--;
        }
    }
}
class Solution {
    public String reverseStr(String s, int k) {
        StringBuffer result = new StringBuffer();
        int start = 0;
        while (start < s.length()) {
            StringBuffer temp = new StringBuffer();
            int firstK = start + k < s.length() ? start + k : s.length();
            int secondK = start + 2 * k < s.length() ? start + 2 * k : s.length();

            temp.append(s.substring(start, firstK));
            result.append(temp.reverse());

            if (firstK < secondK)
                result.append(s.substring(firstK, secondK));
            start += 2 * k;
        }
        return result.toString();
    }
}

剑指 Offer 05. 替换空格

Description

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

Approach

Two pointers

  • Expand the size of the array to the size after replacing each space with “%20”
  • Initialize pointer left points to the end of the previous array, right to the end of the expanded array.
  • Traverse from left:
    • If s[left]= ' ', replace it with “%20”; else let s[left] = s[right]
    • left--, right--

Solution

class Solution {
    public String replaceSpace(String s) {
        if (s == null || s.length() == 0)
            return s;
        StringBuilder sb = new StringBuilder();
        for (char c: s.toCharArray()) {
            if (c == ' ')
                sb.append("  ");
        }

        int left = s.length() - 1;
        s += sb.toString();
        int right = s.length() - 1;
        char[] ch = s.toCharArray();
        while (left >= 0) {
            if (ch[left] == ' ') {
                ch[right--] = '0';
                ch[right--] = '2';
                ch[right] = '%';
            }
            else
                ch[right] = ch[left];
            right--;
            left--;
        }
        return new String(ch);
    }
}

151. Reverse Words in a String

Link: https://leetcode.com/problems/reverse-words-in-a-string/

Description

Given an input string s, reverse the order of the words.

A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.

Return a string of the words in reverse order concatenated by a single space.

Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.

Approach

Two pointers

  1. Remove redundant spaces:
    • Remove the spaces at the start and spaces at the end.
    • Remove the redundant spaces between the words:
      • If the previous element of a space is a character, remove it
  2. Reverse the array
    • Initialize two pointers start and end
    • Swap start and end, then both pointers move towards the middle at the same time
    • Stop when start and end meet.
  3. Reverse each word
    • Initialize two pointers start and end
    • Traverse the array:
      • Let start points to the start of a word, end points to the end of the word, which is the element before the space.
      • Reverse the word, then let start and end points to the next word

Solution

class Solution {
    public String reverseWords(String s) {
        StringBuilder sb = removeSpace(s);
        reverseString(sb, 0, sb.length() - 1);
        return reverseEachWord(sb);
    }

    private StringBuilder removeSpace(String s) {
        char[] ch = s.toCharArray();
        int start = 0;
        int end = s.length() - 1;
        StringBuilder sb = new StringBuilder();
        while (ch[start] == ' ')
            start++;
        while (ch[end] == ' ')
            end--;
        while (start <= end) {
            char c = ch[start];
            if (c != ' ' || sb.charAt(sb.length() - 1) != ' ')
                sb.append(c);
            start++;
        }
        return sb;
    }

    private void reverseString(StringBuilder sb, int start, int end) {
        while (start < end) {
            char temp = sb.charAt(start);
            sb.setCharAt(start, sb.charAt(end));
            sb.setCharAt(end, temp);
            start++;
            end--;
        }
    }

    private String reverseEachWord(StringBuilder sb) {
        int start = 0;
        int end = 1;
        while (start < sb.length()) {
            while (end < sb.length() && sb.charAt(end) != ' ')
                end++;
            reverseString(sb, start, end - 1);
            start = end + 1;
            end = start + 1;
        }
        return sb.toString();
    }
}

剑指Offer58-II.左旋转字符串

Link: https://leetcode.cn/problems/zuo-xuan-zhuan-zi-fu-chuan-lcof/

Description

字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。请定义一个函数实现字符串左旋转操作的功能。比如,输入字符串"abcdefg"和数字2,该函数将返回左旋转两位得到的结果"cdefgab"。

Approach

  1. Reverse the first n character
  2. Reverse the remain characters
  3. Reverse the whole String

Solution

class Solution {
    public String reverseLeftWords(String s, int n) {
        StringBuilder sb= new StringBuilder(s);
        reverseString(sb, 0, n - 1);
        reverseString(sb, n, s.length() - 1);
        return sb.reverse().toString();
    }
    private void reverseString(StringBuilder sb, int start, int end) {
        while (start < end) {
            char temp = sb.charAt(start);
            sb.setCharAt(start, sb.charAt(end));
            sb.setCharAt(end, temp);
            start++;
            end--;
        }
    }
}

你可能感兴趣的:(leetcode,算法)