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

来源:互联网 发布:手机控制网络的软件 编辑:程序博客网 时间:2024/05/16 04:59


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_tint 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
原创粉丝点击