题解 | #字符串变形#

字符串变形

https://www.nowcoder.com/practice/c3120c1c1bc44ad986259c0cf0f0b80e

import java.util.*;

public class Solution {
    public String trans(String s, int n) {
        // write code here
        if (s == null || s.length() < 1 || n < 1) {
            return s;
        }
        char[] arr = s.toCharArray();
        reverse(arr, 0, n - 1);
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            if (arr[i] == ' ') {
                list.add(i);
            }
        }
        if (list.size() == 0) {
            reverse(arr, 0, n - 1);
            convert(arr, 0, n - 1);
            return new String(arr);
        }

        int l = 0;
        int r = 0;
        for (int i = 0; i < list.size(); i++) {
            if (i == 0 && list.get(i) == 0) {
                continue;
            } else if (i == 0 && list.get(i) != 0) {
                l = 0;
            } else {
                l = list.get(i - 1) + 1;
            }
            r = list.get(i) - 1;
            if (l != r) {
                reverse(arr, l, r);
            }
            convert(arr, l, r);
        }
        r = list.get(list.size() - 1);
        if (r != n - 1) {
            reverse(arr, r + 1, n - 1);
            convert(arr, r + 1, n - 1);
        } 

        return new String(arr);
    }

    private void reverse(char[] arr, int l, int r) {
        while (l < r) {
            char tmp = arr[l];
            arr[l] = arr[r];
            arr[r] = tmp;
            l++;
            r--;
        }
    }

    private void convert(char[] arr, int l, int r) {
        for (int i = l; i <= r; i++) {
            if (Character.isLowerCase(arr[i])) {
                arr[i] = (char) (arr[i] - 'a' + 'A');
            } else {
                arr[i] = (char) (arr[i] - 'A' + 'a');  
            }
        }
    }
}

全部评论

相关推荐

孤寡孤寡的牛牛很热情:为什么我2本9硕投了很多,都是简历或者挂,难道那个恶心人的测评真的得认真做吗
点赞 评论 收藏
分享
牛客279957775号:铁暗恋
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务