反转元音字母

编写一个函数,以字符串作为输入,反转该字符串中的元音字母。

示例 1:

输入: "hello"
输出: "holle"

示例 2:

输入: "leetcode"
输出: "leotcede"

说明:
元音字母不包含字母"y"。
package newhomework;

public class ssss {
	public static void main(String[] args) {
		String string = "xzvgdvbsd";
		System.out.println(xxxx(string));
		System.out.print(xxxx1(string));
	}
	/**
	 * 反转字符串中的元音字母
	 * hello
	 * 从两边网往中间查找,每找到一位元音字母就换位置
	 * 执行用时 :1428 ms
	 * 内存消耗 :41.9 MB
	 * @param s
	 * @return
	 */
	public static String xxxx(String s) {
		//排除掉空串,或空格
		if (s==null||s.trim().isEmpty()) {
			return s;
		}
		//转字符数组
		char[] c = s.toCharArray();
		//长度
		int l = c.length;
		//左边开始和右边开始的数组下标
		String a = "", b = "";
		//找元音字母
		for (int i = 0; i < l; i++) {
			if (c[i] == 'a' || c[i] == 'e' || c[i] == 'i' || c[i] == 'o' || c[i] == 'u' || c[i] == 'A' || c[i] == 'E'
					|| c[i] == 'I' || c[i] == 'O' || c[i] == 'U') {
				a += i + ",";
			}
		}
		for (int i = l - 1; i >= 0; i--) {
			if (c[i] == 'a' || c[i] == 'e' || c[i] == 'i' || c[i] == 'o' || c[i] == 'u' || c[i] == 'A' || c[i] == 'E'
					|| c[i] == 'I' || c[i] == 'O' || c[i] == 'U') {
				b += i + ",";
			}
		}
		//切割是元音字母的下标
		String[] x = a.split(",");
		String[] y = b.split(",");
		//如果这串没有元音字母,则直接返回
		if (a.trim().isEmpty()) {
			return s;
		}
		//交换位置
		for (int j = 0; j < y.length; j++) {
			//左边第一个起的元音字母
			int n = Integer.parseInt(x[j]);
			//右边第一个起的元音字母
			int m = Integer.parseInt(y[j]);
			//往中间查找交换,各一半
			if (n < m) {
				char temp = c[n];
				c[n] = c[m];
				c[m] = temp;

			}
		}
		//交换后的字符串
		return String.valueOf(c);
	}
	

	/**
	 * 从两边网往中间查找,每找到一位元音字母就换位置
	 * 执行用时 :2 ms, 在所有 java 提交中击败了100.00% 的用户
	 * 内存消耗 :37 MB, 在所有 java 提交中击败了97.99%的用户
	 * @param s
	 * @return
	 */
	public static String xxxx1(String s) {
		char[] condition = s.toCharArray();
		boolean [] bool = new boolean[128];
		bool['A'] = true;bool['a'] = true;
		bool['E'] = true;bool['e'] = true;
		bool['I'] = true;bool['i'] = true;
		bool['O'] = true;bool['o'] = true;
		bool['U'] = true;bool['u'] = true;
		int start = 0,end = s.length()-1;
		while (start<end) {
			if (!bool[condition[start]]) {
				start++;
			}else if (!bool[condition[end]]) {
				end--;
			}else {
				char temp = condition[start];
				condition[start] = condition[end];
				condition[end] = temp;
				start++;
				end--;
			}
		}
		return String.valueOf(condition);
	}

}

猜你喜欢

转载自blog.csdn.net/weixin_41367523/article/details/102640821
今日推荐