Reverse Words in a String LeetCode 151 Java Solution

🚀 DSA Learning Update – Reverse Words in a String Today I solved “Reverse Words in a String” (LeetCode #151) using a clean and practical approach. 🔍 Problem Insight The goal is not just reversing a string, but: Removing extra spaces Keeping only single spaces between words Reversing the order of words 💡 My Approach Trim the string to remove leading/trailing spaces Split the string using " " Traverse from right → left Skip empty strings (caused by multiple spaces) Build the result using StringBuilder 📌 Core Logic String str = s.trim(); String[] ar = str.split(" "); StringBuilder ans = new StringBuilder(); for (int i = ar.length - 1; i >= 0; i--) { if (ar[i].equals("")) continue; if (ans.length() > 0) { ans.append(" "); } ans.append(ar[i]); } return ans.toString(); 📌 Example Input: " hello world " Output: "world hello" 🧠 Key Learnings ✔ Always handle edge cases (especially spaces in strings) ✔ split(" ") can create empty values → must filter them ✔ Reversing traversal simplifies the logic ✔ Clean formatting matters as much as correctness ✨ Takeaway Even simple string problems can test attention to detail. Learning how to handle edge cases properly is a big step toward writing robust code. #DSA #LeetCode #Java #ProblemSolving #CodingJourney #LearnInPublic #SoftwareEngineering

  • graphical user interface, application

To view or add a comment, sign in

Explore content categories