思路:切割+反向拼接(Java)

翻转单词顺序列

http://www.nowcoder.com/questionTerminal/3194a4f4cf814f63919d0790578d51f3

1、借助库函数split实现

    public static String  ReverseSentence(String str) {
        if(str == null || str.length() ==0)return str;
        String[] strings = str.split(" ");
        if(strings.length == 0)return str;
        StringBuilder res = new StringBuilder();
        for(int i = strings.length - 1;i>=0;i--){
            res.append(strings[i]).append(" ");
        }
        return res.toString().trim();
    }

2、自己实现库函数split功能

    public  static String  ReverseSentence(String str) {
        if(str == null || str.length() ==0 ||"".equals(str.trim()))return str;
        ArrayList<String> list = new ArrayList<>();
        StringBuilder res = new StringBuilder();
        StringBuilder sb = new StringBuilder();
        for(int i = 0;i<str.length();i++){
            if(str.charAt(i) == ' '||(i == str.length() - 1)){
                list.add(sb.append(str.charAt(i)==' '?"":str.charAt(i)).toString());
                sb = new StringBuilder("");
            }else{
                sb.append(str.charAt(i));
            }
        }
        String[] result = new String[list.size()];
        result =  (String[])list.subList(0, list.size()).toArray(result);
        for(int i = result.length - 1;i>=0;i--){
            res.append(result[i]).append(" ");
        }
        return res.toString().trim();
    }
全部评论

相关推荐

10-28 15:45
门头沟学院 C++
西南山:海康威视之前不是大规模裁员吗
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务