Thursday, April 21, 2016

Remove Vowels From A String in Place

April 21, 2016

Work on algorithm called "Remove Vowels From A String in Place ".

problem statement see the blog:
https://www.careercup.com/question?id=2698

Take any word, remove vowels and place them in reverse order by untouching consonants and place them back. Word is AIRPLANE.

HackerRank has one algorithm, but only 4 submissions:

https://www.hackerrank.com/contests/knockout-coding/challenges/pair-odd

Read the blog about "Remove vowels":
http://shashank7s.blogspot.ca/2011/03/wap-to-remove-remove-vowels-from-string.html

https://www.quora.com/How-do-I-remove-vowels-from-a-string

Question and Answer:
Walk through the code, add comments:


  1. const string vowels = "aeiou"; // Julia: all vowels in a string
  2. void remVowels(string &s){
  3. int k=0; // pointer: int k, mark the next available position for non vowel char
  4. for(int i=0; i<s.length(); i++){ // Julia: go through the string once, in a loop
  5. if(vowels.find(s[i]) == string::npos) // if current char is not a vowel
  6. s[k++] = s[i];
  7. // skip vowel, do nothing.
  8. }
  9. s.resize(k); // mark the end of the string removing all vowels.
  10. }
Read api how resize is defined in C++:
http://www.cplusplus.com/reference/string/string/resize/

4 comments:

  1. Hi Julia,
    I came across this post on your blog as I was learning on my own. I am curious as to how you come up with your solution? I'm still having some issues understanding the logic.
    I also wanted to point out that you missed the reversing portion of the question but that can be fixed by calling reverse(s.begin(), s.end());

    ReplyDelete
    Replies
    1. Here is my approach to things
      https://github.com/ajsingh4/RemoveVowelsFromString

      I definitely wasn't aware of resize or string::npos.
      My email is ajgill@ucdavis.edu

      Thanks,

      Delete
  2. Gill, thank you to ask me the questions. I read your code and also read my post here as well. It is an interesting question.
    To remove vowels from a string in place, there are two things, first is to remove vowels, and the second is to stay in place. Since the string with removed vowels is shorter than original string, it is a working idea to put back in the same string starting from index 0.
    To reverse the string is not asked in the problem statement: remove vowels from a string in place.

    ReplyDelete
  3. Ahhh you are correct, thank you!
    I realized that you used something similar to slow-fast pointer in your approach to this.
    So essentially you are putting in all of the consonants that you come across at the beginning of the string, overwriting what is there and providing you with a string of just consonants, correct?
    Thank you very much for your help.

    ReplyDelete