首页 > 代码库 > LeetCode | Reverse Words in a String(C#)
LeetCode | Reverse Words in a String(C#)
题目:
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
代码:
public static string reverseWords(string str) { string reverStr = ""; int count = 0; Stack stack1 = new Stack(); Stack stack2 = new Stack(); foreach (var item in str) { if(item==‘ ‘) { stack1.Push(item); count = stack1.Count; for (int i = 0; i < count; i++) { stack2.Push(stack1.Pop()); } } else { stack1.Push(item); } } stack2.Push(‘ ‘); count = stack1.Count; for (int i = 0; i < count; i++) { stack2.Push(stack1.Pop()); } count = stack2.Count - 1; for (int i = 0; i < count; i++) { reverStr = reverStr + stack2.Pop().ToString(); } return reverStr; }
LeetCode | Reverse Words in a String(C#)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。