剑指offer-20200318

20200318

题目 :和为s的连续正数序列

输入一个正整数 target ,输出所有和为 target 的连续正整数序列(至少含有两个数)。

序列内的数字由小到大排列,不同序列按照首个数字从小到大排列。

思路 :利用一个滑动窗口

code

class Solution{
    public int[][] findContinuousSequence(int target){
        List<int[]> list = new ArrayList<>();
        for(int l=1,r=1;sum=0,r < target;r++){
            sum += r;
            while(sum > target){
                sum -= l++;
            }
            if(sum == target){
                int[] temp = new int[r - l + 1];
                for(int i=0;i<temp.length;i++){
                    temp[i] = l + i;
                }
                list.add(temp);
            }
        }
        
        int[][] res = new int[list.size()][];
        for(int i=0;i<res.length;i++){
            res[i] = list.get(i);
        }
        return res;
    }
}

题目 :反转单词顺序

输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。为简单起见,标点符号和普通字母一样处理。例如输入字符串"I am a student. “,则输出"student. a am I”。

code

public String reverseWords(String s){
    //将传进来的字符串以空格拆分
    String[] strings = s.trim().split(" ");
    StringBuffer stringBuffer = new StringBuffer();
    //从尾部开始遍历
    for(int i=strings.length - 1;i >= 0;i--){
        if(strings[i].equal("")){
            continue;
        }
        if(i==0){
            stringBuffer.append(strings[i].trim());
        }else{
            stringBuffer.append(string[i].trim()).append(" ");
        }
    }
    return stringBuffer.toString();
}
发布了94 篇原创文章 · 获赞 13 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_31900497/article/details/104938028