题解 | #字符串变形#

字符串变形

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

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param s string字符串 
     * @param n int整型 
     * @return string字符串
     */
    public String trans (String s, int n) {
        // write code here
        List<String> res = new ArrayList<>();
        for(int i=0; i<n; ){
            char ch = s.charAt(i);
            StringBuilder sb = new StringBuilder();
            if(Character.isLetter(ch)){
                sb = new StringBuilder();
                while(i < n && Character.isLetter(s.charAt(i))){
                    sb.append(charReverse(s.charAt(i)));
                    i++;
                }
            }
            if(!Character.isLetter(ch)){
                sb = new StringBuilder();
                while(i < n && !Character.isLetter(s.charAt(i))){
                    sb.append(charReverse(s.charAt(i)));
                    i++;
                }
            }
            res.add(sb.toString());
        }
        StringBuilder strSb = new StringBuilder();
        for(int i=res.size()-1; i>=0; i--){
            strSb.append(res.get(i));
        }
        return strSb.toString();

    }

    char charReverse(char ch){
        if('a' <= ch && ch <= 'z'){
            return (char)(ch-32);
        }
        if('A' <= ch && ch <= 'Z'){
            return (char)(ch+32);
        }
        return ch;
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享
牛客网
牛客企业服务