Interview 150
Reverse String
- Problem
- LC 344
- File
- interview150_LC344ReverseString.java
- Path
- pkg5leetcode/interview150/interview150_LC344ReverseString.java
- Package
- pkg5leetcode.interview150
- Command
- java pkg5leetcode/interview150/interview150_LC344ReverseString.java
- Approach
- Two pointers swap chars from both ends.
- Complexity
- Time O(n), Space O(1)
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg5leetcode.interview150;2 3/*4 * Reverse String | LC 3445 * APPROACH: Two pointers swap chars from both ends.6 * COMPLEXITY: Time O(n), Space O(1)7 */8public class interview150_LC344ReverseString {9 static void reverseString(char[] s) {10 int l = 0, r = s.length - 1;11 while (l < r) {12 char t = s[l];13 s[l++] = s[r];14 s[r--] = t;15 }16 }17 18 public static void main(String[] args) {19 char[] a = {'h', 'e', 'l', 'l', 'o'};20 reverseString(a);21 check(new String(a).equals("olleh"), "case1");22 char[] b = {'H', 'a', 'n', 'n', 'a', 'h'};23 reverseString(b);24 check(new String(b).equals("hannaH"), "case2");25 System.out.println("all tests passed");26 }27 28 static void check(boolean cond, String name) {29 if (!cond) throw new AssertionError("FAILED: " + name);30 System.out.println(" PASS " + name);31 }32}