ReverseWord & ReverseWordsTest (#2022)

* ReverseWord & ReverseWordsTest

* ReverseWord & ReverseWordsTest

* fixed ReverseWords

* Merge branch 'master' of https://github.com/TheAlgorithms/Java into Development
This commit is contained in:
Lovesh Dongre 2020-11-22 23:14:40 +05:30 committed by GitHub
parent 546bc3f5c8
commit 1012ff74f3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 45 additions and 0 deletions

View File

@ -0,0 +1,30 @@
package com.strings;
public class ReverseWords {
/**
* Converts all of the words in this {@code String} to reversed words
*
* @param s the string to convert
* @return the {@code String}, converted to a string with reveresed words.
*/
public String returnReverseWords(String s) {
StringBuilder sb = new StringBuilder();
StringBuilder word = new StringBuilder();
for(int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if(c == ' ') {
sb.append(word);
sb.append(" ");
word.setLength(0);
continue;
}
word.insert(0, c);
}
sb.append(word);
return sb.toString();
}
}

View File

@ -0,0 +1,15 @@
package com.string;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class ReveresWordsTest {
@Test
void testReverseWords() {
ReverseWords reverseWords = new ReverseWords();
Assertions.assertEquals(true, reverseWords.returnReverseWords("this is my car"), "siht si ym rac");
Assertions.assertEquals(true, reverseWords.returnReverseWords("ABC 123"), "CBA 321");
}
}