【编程】【leetcode】345.Reverse Vowels of a String


c++

 string::find_first_of
//#include <iostream>       // std::cout
//#include <string>         // std::string
//#include <cstddef>        // std::size_t
//
//int main()
//{
//	std::string str("Please, replace the vowels in this sentence by asterisks.");
//	//第一点:pl不是说一个组合,而是说字符串中的任意一个字符都可以,p或者l或者是pl
//	//第二点:找到返回位置,找不到返回npos
//	std::size_t found = str.find_first_of("pl"); 
//	std::size_t found2 = str.find_first_of("s",0);
//	str[found2] = '$';
//	//第三点:0或者是不写表示从字符串开头开始,找到第一个匹配的字符。写了表示从此坐标开始往后查找
//	while (found != std::string::npos)
//	{
//		str[found] = '*';
//		found = str.find_first_of("pl", found + 1);
//	}
//
//	std::cout << str << '\n';
//
//	return 0;
//}


// string::find_first_not_of
#include <iostream>       // std::cout
#include <string>         // std::string
#include <cstddef>        // std::size_t

int main()
{
	std::string str("look for non-alphabetic characters...");

	//Searches the string for the first character that does not match any of the characters specified in its arguments.
	std::size_t found = str.find_first_not_of("abcdefghijklmnopqrstuvwxyz ");

	if (found != std::string::npos)
	{
		std::cout << "The first non-alphabetic character is " << str[found];
		std::cout << " at position " << found << '\n'; //返回的结果是12,也就是说字符串的下标是从零开始的
	}

	return 0;
}


class Solution {
public:
	string reverseVowels(string s) {
		int i = 0, j = s.size() - 1;
		while (i < j) {
            i = s.find_first_of("aeiouAEIOU", i);  //在first中position表示起始查找位置
            j = s.find_last_of("aeiouAEIOU", j);   //在last中position表示结束查找的位置
            if (i < j) {
                swap(s[i++], s[j--]);  //先进行换的操作,再进行自增和自减操作
            }
        }
        return s;
    }
};

java

/**
find_last_of中j表示终止位置,而在Java中lastindexof中j表示起始位置 所以不能直接将c++代码思路装转换成java
*/
public class Solution {
	static final String vowels = "aeiouAEIOU";
	public String reverseVowels(String s) {
		int first = 0, last = s.length() - 1;
		char[] array = s.toCharArray();
		while(first < last){
			while(first < last && vowels.indexOf(array[first]) == -1){
				first++;
			}
			while(first < last && vowels.indexOf(array[last]) == -1){
				last--;
			}
			char temp = array[first];
			array[first] = array[last];
			array[last] = temp;
			first++;
			last--;
		}
		return new String(array);
	}
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值