java - Are the following two "Swap Vowels in a String" solutions computationally equivalent? -


i wondering if following 2 solutions "swap vowels in string" problem computationally equivalent (time complexity & memory).

solution 1 (main for loop conditional nested for) :

package practicequestions.p1;      import java.util.hashset;      public class solution {          public static char[] solve (string text) {             hashset vowelset = new hashset();             char[] vowels = {'a','e','i','o','u','a','e','i','o','u'};              (char v : vowels) {                 vowelset.add(v);             }              char[] aschararray = text.tochararray();             int laststop = aschararray.length;              (int = 0; < laststop; i++) {                 if(vowelset.contains(aschararray[i])) {                     (int j = laststop - 1; j > i; j--) {                         if(vowelset.contains(aschararray[j])) {                             char temp = aschararray[j];                             aschararray[j] = aschararray[i];                             aschararray[i] = temp;                              laststop = j;                             break;                         }                     }                 }             }              return aschararray;         }          public static void main(string[] args) {             string sometext = "swap vowels";             system.out.println(solution.solve(sometext));         }      } 

solution 2 (i don't have code, here explanation) :

there main while loop starts both ends of string , stores vowels in hashmap integer key , character value. then, based on position (key) of each value, function swap vowel characters (value).

are 2 mentioned above computationally equivalent? know sure solution 2 more tasking on memory, i'm not sure time complexity. i'm guessing solution 1 faster.

this isn't going terribly rigorous, believe should hold. n length of input string, , we're considering worst case entire string vowels...

method 1
time: n*(time swap) + constants
nested partial loops work out 1 complete loop.
space: n + constants
storing input string, vowel dictionary, , few counters/swap variables

method 2
time: n*(time insert in hashmap) + n*(time find , swap) + constant
you're doing way more computation in 1 other one. instead of 3 operation swap, you're computing hash code , inserting element. afterwards, actual replacement.
space: (some multiple of n) + constants
hash map take amount of space each element in addition space required method 1.

hope helps.


Comments

Popular posts from this blog

sql - VB.NET Operand type clash: date is incompatible with int error -

SVG stroke-linecap doesn't work for circles in Firefox? -

python - TypeError: Scalar value for argument 'color' is not numeric in openCV -