LeetCode 345 —— 反转字符串中的元音字母

https://leetcode-cn.com/problems/reverse-vowels-of-a-string/

class Solution {
     
    public String reverseVowels(String s) {
     
        char[] sToChar = s.toCharArray();
		char[] vowels = {
     'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'};
		int i=0, j=sToChar.length-1;
		char charI='1', charJ='1';
		for(;i<=j && i<sToChar.length && j>=0;) {
     
			System.out.println("i::" + i + "::j::" + j);
			if(sToChar[i]=='a' || sToChar[i]=='e' || sToChar[i]=='i' || sToChar[i]=='o'  || sToChar[i]=='u' || sToChar[i]=='A'  || sToChar[i]=='E'  || sToChar[i]=='I'  || sToChar[i]=='O'  || sToChar[i]=='U') {
     
				charI = sToChar[i];
			}else {
     
				i++;
			}
			
			if(sToChar[j]=='a' || sToChar[j]=='e' || sToChar[j]=='i' || sToChar[j]=='o' || sToChar[j]=='u'|| sToChar[j]=='A'  || sToChar[j]=='E'  || sToChar[j]=='I'  || sToChar[j]=='O'  || sToChar[j]=='U') {
     
				charJ = sToChar[j];
			}else {
     
				j--;
			}
			
			if(charI != '1' && charJ != '1') {
     
				System.out.println(";;;;;;;;;" + "i::" + i + "::j::" + j);
				char temp = charI;
				sToChar[i] = sToChar[j];
				sToChar[j] = temp;
				i++;
				j--;
				charI = '1';
				charJ = '1';
			}
			
		}
		StringBuilder sb = new StringBuilder();
		for(int q=0;q<sToChar.length;q++) {
     
			sb.append(sToChar[q]);
		}
		return sb.toString();
    }
}

代码改进:

class Solution {
     
    public String reverseVowels(String s) {
     
         char[] sToChar = s.toCharArray();
		//char[] vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'};
		int i=0, j=sToChar.length-1;
	
		while(i<j) {
     
			System.out.println("i::" + i + "::j::" + j + "::sToChar[i]::" + sToChar[i] + "::sToChar[j]::" + sToChar[j]);
			while(!judgeVowels(sToChar[i]) && i<sToChar.length-1) {
     
				System.out.println("111:::i::" + i);
				i++;
			}
			while(!judgeVowels(sToChar[j]) && j>0) {
     
				System.out.println("111:::j::" + j);
				j--;
			}
			if(i>=j) break;
			
			char temp = sToChar[i];
			sToChar[i++] = sToChar[j];
			sToChar[j--] = temp;	
			
		}
		StringBuilder sb = new StringBuilder();
		for(int q=0;q<sToChar.length;q++) {
     
			sb.append(sToChar[q]);
		}
		return sb.toString();
    }

     public static boolean judgeVowels(char c){
     
	        if(c=='a' || c=='e' || c=='i' || c=='o' || c=='u' || c=='A' || c=='E' || c=='I' || c=='O' || c=='U'){
     
	            return true;
	        }else{
     
	        	return false;
	        }
	 }
}

但是,内存和时间消耗还是大,
改进交换数组位置:

			//元音字母互换
            chars[l] = (char) (chars[l] + chars[r]);
            chars[r] = (char) (chars[l] - chars[r]);
            chars[l] = (char) (chars[l] - chars[r]);
           //这种是容易看懂的替换,但是内存消耗看着有点大
            // char temp = chars[l];
            // chars[l] = chars[r];
            // chars[r] = temp;

LeetCode 345 —— 反转字符串中的元音字母_第1张图片

你可能感兴趣的:(LeetCode,数据结构)