11/2 下午 <String>

344. Reverse String

解法一(暴力法):

直接从两头往中间走,同时交换两边的字符即可

首位对调位置。

class Solution {
    public void reverseString(char[] s) {
        int tail = s.length-1;
        for(int i = 0; i < s.length/2; i++){
            char temp = s[i];
            s[i] = s[tail-i];
            s[tail-i] = temp;
        }
    }
}

解法二:

利用swap函数求解

class Solution {
    public void reverseString(char[] s) {
        // if(s == null || s.length == 0)
        //     return "";
        
        int left = 0, right = s.length-1;
        while(left < right){
            char temp = s[left];
            s[left++] = s[right];
            s[right--] = temp;
        }
    }
}

151. Reverse Words in a String

1.反转全部字符数组

2.反转每个单词

3.清楚多余空格

class Solution {
    public String reverseWords(String s) {
        int n = s.length();
        if (n == 0)
            return "";
        
        char[] a = s.toCharArray();
        //1. reverse string
        reverse(a, 0, n - 1);
        //2. reverse words
        reverseWord(a, n);
        //3. clean up spaces
        return cleanSpaces(a,n);
    }
    public String cleanSpaces(char[] a, int n){
        int i = 0, j = 0;
        while(j < n){
            while(j < n && a[j] == ' ') j++;
            while(j < n && a[j] != ' ') a[i++] = a[j++]; //keep non-spaces
            while(j < n && a[j] == ' ') j++;
            if(j < n) a[i++] = ' '; //keep only one space
        }
         return new String(a).substring(0, i);
    }
    
     void reverseWord(char[] a, int n){
        int i = 0, j = 0;
        while(i < n){
            while(i < j || i < n && a[i] == ' ') i++; //skip spaces
            while(j < i || j < n && a[j] != ' ') j++; //skip non-spaces
            reverse(a, i, j -1);
        }
    }
    
    private void reverse(char[] a, int i, int j){
        while(i < j){
            char temp = a[i];
            a[i++] = a[j];
            a[j--] = temp;
        }
    }
}

1.String类中toCharArray()方法的用法

 该方法的作用是返回一个字符数组,该字符数组中存放了当前字符串中的所有字符。将字符串转换为字符数组。

2. 数组有length属性,String有length()方法。

优先级&& 大于 ||

猜你喜欢

转载自www.cnblogs.com/Afei-1123/p/11783100.html