关于算法:算法-字符串-反转字符串

34次阅读

共计 1218 个字符,预计需要花费 4 分钟才能阅读完成。

题目 1

力扣 344 题,反转字符串

 编写一个函数,其作用是将输出的字符串反转过去。输出字符串以字符数组 s 的模式给出。不要给另外的数组调配额定的空间,你必须原地批改输出数组、应用 O(1) 的额定空间解决这一问题。示例 1:输出:s = ["h","e","l","l","o"]
输入:["o","l","l","e","h"]
示例 2:输出:s = ["H","a","n","n","a","h"]
输入:["h","a","n","n","a","H"]

起源:力扣(LeetCode)链接:https://leetcode.cn/problems/reverse-string
著作权归领扣网络所有。商业转载请分割官网受权,非商业转载请注明出处。

解法:双指针

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

题目 2

力扣 541 题 反转字符串 II

 给定一个字符串 s 和一个整数 k,从字符串结尾算起,每计数至 2k 个字符,就反转这 2k 字符中的前 k 个字符。如果残余字符少于 k 个,则将残余字符全副反转。如果残余字符小于 2k 但大于或等于 k 个,则反转前 k 个字符,其余字符放弃原样。示例 1:输出:s = "abcdefg", k = 2
输入:"bacdfeg"
示例 2:输出:s = "abcd", k = 2
输入:"bacd"

起源:力扣(LeetCode)链接:https://leetcode.cn/problems/reverse-string-ii
著作权归领扣网络所有。商业转载请分割官网受权,非商业转载请注明出处。

解法:双指针

class Solution {public String reverseStr(String s, int k) {char[] chars = s.toCharArray();

        int length = chars.length;

        for(int i = 0; i*k < length; i++){if(i%2 == 0){
                int end = i*k+k-1;
                if (i*k+k-1 >= length){end = length-1;}
                reverseArray(chars, i*k, end);
            }
        }

        return new String(chars);
    }
    
    // 反转数组区间
    public void reverseArray(char[] chars, int start, int end) {
        int offset = 0;
        for(int i = start; i <= (start+end)/2; i++){char tmp = chars[start + offset];
            chars[start + offset] = chars[end - offset];
            chars[end - offset] = tmp;
            offset++;
        }
    }
}

正文完
 0