C# 在不使用字符串的情况下反转句子中的单词。在C中拆分
最近,在一次讨论中,我被要求编写一个算法,以实现句子单词的反转,而不是整个句子的反转,而不使用字符串操作,例如除tocharray和Length之外的Split/Replace/reverse/Join。下面是我能在5分钟内想出的。虽然算法运行良好,但它的实现风格似乎有点难看。有人能帮我润色一下密码吗C# 在不使用字符串的情况下反转句子中的单词。在C中拆分,c#,.net,string,algorithm,C#,.net,String,Algorithm,最近,在一次讨论中,我被要求编写一个算法,以实现句子单词的反转,而不是整个句子的反转,而不使用字符串操作,例如除tocharray和Length之外的Split/Replace/reverse/Join。下面是我能在5分钟内想出的。虽然算法运行良好,但它的实现风格似乎有点难看。有人能帮我润色一下密码吗 string ReverseWords(string s) { string reverseString = string.Empty; string word = string.
string ReverseWords(string s)
{
string reverseString = string.Empty;
string word = string.Empty;
var chars = s.ToCharArray();
List<ArrayList> words = new List<ArrayList>();
ArrayList addedChars = new ArrayList();
Char[] reversedChars = new Char[chars.Length];
int i = 1;
foreach (char c in chars)
{
if (c != ' ')
{
addedChars.Add(c);
}
else
{
words.Add(new ArrayList(addedChars));
addedChars.Clear();
}
if (i == s.Length)
{
words.Add(new ArrayList(addedChars));
addedChars.Clear();
}
i++;
}
foreach (ArrayList a in words)
{
for (int counter = a.Count - 1; counter >= 0; counter--)
{
reverseString += a[counter];
}
if(reverseString.Length < s.Length)
reverseString += " ";
}
return reverseString;
}
有一个相对优雅的解决方案,它使用后进先出堆栈。
这个问题听起来像是家庭作业,所以我只提供伪代码
currWord = new LIFO stack of characters
while (! end of string/array)
{
c = next character in string/array
if (c == some_white_space_character) {
while (currWord not empty) {
c2 = currWord.pop()
print(c2)
}
print(c)
}
else
currWord.push(c)
}
有一个相对优雅的解决方案,它使用后进先出堆栈。
这个问题听起来像是家庭作业,所以我只提供伪代码
currWord = new LIFO stack of characters
while (! end of string/array)
{
c = next character in string/array
if (c == some_white_space_character) {
while (currWord not empty) {
c2 = currWord.pop()
print(c2)
}
print(c)
}
else
currWord.push(c)
}
这有点简单:
string inp = "hai how are you?";
StringBuilder strb = new StringBuilder();
List<char> charlist = new List<char>();
for (int c = 0; c < inp.Length; c++ )
{
if (inp[c] == ' ' || c == inp.Length - 1)
{
if (c == inp.Length - 1)
charlist.Add(inp[c]);
for (int i = charlist.Count - 1; i >= 0; i--)
strb.Append(charlist[i]);
strb.Append(' ');
charlist = new List<char>();
}
else
charlist.Add(inp[c]);
}
string output = strb.ToString();
这有点简单:
string inp = "hai how are you?";
StringBuilder strb = new StringBuilder();
List<char> charlist = new List<char>();
for (int c = 0; c < inp.Length; c++ )
{
if (inp[c] == ' ' || c == inp.Length - 1)
{
if (c == inp.Length - 1)
charlist.Add(inp[c]);
for (int i = charlist.Count - 1; i >= 0; i--)
strb.Append(charlist[i]);
strb.Append(' ');
charlist = new List<char>();
}
else
charlist.Add(inp[c]);
}
string output = strb.ToString();
有点像一个完美的版本:-
string words = "hi! how are you!";
string reversedWords = "";
List<int> spaceEncounter = new List<int>();
spaceEncounter.Add(words.Length - 1);
for (int i = words.Length - 1; i > 0; i--)
{
if(words[i].Equals(' '))
{
spaceEncounter.Add(i);
for (int j = i+1; j < spaceEncounter[spaceEncounter.Count - 2]; j++)
reversedWords += words[j];
reversedWords += " ";
}
}
for (int i = 0; i < spaceEncounter[spaceEncounter.Count - 1]; i++)
reversedWords += words[i];
有点像一个完美的版本:-
string words = "hi! how are you!";
string reversedWords = "";
List<int> spaceEncounter = new List<int>();
spaceEncounter.Add(words.Length - 1);
for (int i = words.Length - 1; i > 0; i--)
{
if(words[i].Equals(' '))
{
spaceEncounter.Add(i);
for (int j = i+1; j < spaceEncounter[spaceEncounter.Count - 2]; j++)
reversedWords += words[j];
reversedWords += " ";
}
}
for (int i = 0; i < spaceEncounter[spaceEncounter.Count - 1]; i++)
reversedWords += words[i];
您的代码中有一个小错误。因此,输出字符串将显示为yo are how hi!,给定输入字符串hi!你好吗它正在截断最后一个单词的最后一个字符 更改此项:
spaceEncounter.Add(words.Length - 1);
致:
您的代码中有一个小错误。因此,输出字符串将显示为yo are how hi!,给定输入字符串hi!你好吗它正在截断最后一个单词的最后一个字符 更改此项:
spaceEncounter.Add(words.Length - 1);
致:
字符串温度=字符串为空;
string reversedString=string.Empty;
测试语句中的foreach var currentCharacter
{
如果currentCharacter!=''
{
温度=温度+当前字符;
}
其他的
{
reversedString=temp++reversedString;
temp=string.Empty;
}
}
reversedString=temp++reversedString;
字符串温度=字符串为空;
string reversedString=string.Empty;
测试语句中的foreach var currentCharacter
{
如果currentCharacter!=''
{
温度=温度+当前字符;
}
其他的
{
reversedString=temp++reversedString;
temp=string.Empty;
}
}
reversedString=temp++reversedString;
此版本可以就地工作,没有任何中间数据结构。首先,它反转每个单词中的字符。我也是。然后它反转整个字符串:em oot=>too me
public static string ReverseWords(string s)
{
if (string.IsNullOrEmpty(s))
return s;
char[] chars = s.ToCharArray();
int wordStartIndex = -1;
for (int i = 0; i < chars.Length; i++)
{
if (!Char.IsWhiteSpace(chars[i]) && wordStartIndex < 0)
{
// Remember word start index
wordStartIndex = i;
}
else
if (wordStartIndex >= 0 && (i == chars.Length-1 || Char.IsWhiteSpace(chars[i + 1]))) {
// End of word detected, reverse the chacacters in the word range
ReverseRange(chars, wordStartIndex, i);
// The current word is complete, reset the start index
wordStartIndex = -1;
}
}
// Reverse all chars in the string
ReverseRange(chars, 0, chars.Length - 1);
return new string(chars);
}
// Helper
private static void ReverseRange(char[] chars, int startIndex, int endIndex)
{
for(int i = 0; i <= (endIndex - startIndex) / 2; i++)
{
char tmp = chars[startIndex + i];
chars[startIndex + i] = chars[endIndex - i];
chars[endIndex - i] = tmp;
}
}
此版本可以就地工作,没有任何中间数据结构。首先,它反转每个单词中的字符。我也是。然后它反转整个字符串:em oot=>too me
public static string ReverseWords(string s)
{
if (string.IsNullOrEmpty(s))
return s;
char[] chars = s.ToCharArray();
int wordStartIndex = -1;
for (int i = 0; i < chars.Length; i++)
{
if (!Char.IsWhiteSpace(chars[i]) && wordStartIndex < 0)
{
// Remember word start index
wordStartIndex = i;
}
else
if (wordStartIndex >= 0 && (i == chars.Length-1 || Char.IsWhiteSpace(chars[i + 1]))) {
// End of word detected, reverse the chacacters in the word range
ReverseRange(chars, wordStartIndex, i);
// The current word is complete, reset the start index
wordStartIndex = -1;
}
}
// Reverse all chars in the string
ReverseRange(chars, 0, chars.Length - 1);
return new string(chars);
}
// Helper
private static void ReverseRange(char[] chars, int startIndex, int endIndex)
{
for(int i = 0; i <= (endIndex - startIndex) / 2; i++)
{
char tmp = chars[startIndex + i];
chars[startIndex + i] = chars[endIndex - i];
chars[endIndex - i] = tmp;
}
}
嗯,您没有提到其他LINQ扩展方法:
static string ReverseWordsWithoutSplit(string input)
{
var n = 0;
var words = input.GroupBy(curr => curr == ' ' ? n++ : n);
return words.Reverse().Aggregate("", (total, curr) => total + string.Concat(curr.TakeWhile(c => c != ' ')) + ' ');
}
嗯,您没有提到其他LINQ扩展方法:
static string ReverseWordsWithoutSplit(string input)
{
var n = 0;
var words = input.GroupBy(curr => curr == ' ' ? n++ : n);
return words.Reverse().Aggregate("", (total, curr) => total + string.Concat(curr.TakeWhile(c => c != ' ')) + ' ');
}
一个简单的递归函数检查一个字符串,然后相应地检查子字符串,怎么样
private static string rev(string inSent) {
if(inSent.IndexOf(" ") != -1)
{
int space = inSent.IndexOf(" ");
System.Text.StringBuilder st = new System.Text.StringBuilder(inSent.Substring(space+1));
return rev(st.ToString()) + " " + inSent.Substring(0, space);
}
else
{
return inSent;
}
}
一个简单的递归函数检查一个字符串,然后相应地检查子字符串,怎么样
private static string rev(string inSent) {
if(inSent.IndexOf(" ") != -1)
{
int space = inSent.IndexOf(" ");
System.Text.StringBuilder st = new System.Text.StringBuilder(inSent.Substring(space+1));
return rev(st.ToString()) + " " + inSent.Substring(0, space);
}
else
{
return inSent;
}
}
下面给出了一个最简单的答案,请仔细阅读
public static string ReversewordString(string Name)
{
string output="";
char[] str = Name.ToCharArray();
for (int i = str.Length - 1; i >= 0; i--)
{
if (str[i] == ' ')
{
output = output + " ";
for (int j = i + 1; j < str.Length; j++)
{
if (str[j] == ' ')
{
break;
}
output=output+ str[j];
}
}
if (i == 0)
{
output = output +" ";
int k = 0;
do
{
output = output + str[k];
k++;
} while (str[k] != ' ');
}
}
return output;
}
下面给出了一个最简单的答案,请仔细阅读
public static string ReversewordString(string Name)
{
string output="";
char[] str = Name.ToCharArray();
for (int i = str.Length - 1; i >= 0; i--)
{
if (str[i] == ' ')
{
output = output + " ";
for (int j = i + 1; j < str.Length; j++)
{
if (str[j] == ' ')
{
break;
}
output=output+ str[j];
}
}
if (i == 0)
{
output = output +" ";
int k = 0;
do
{
output = output + str[k];
k++;
} while (str[k] != ' ');
}
}
return output;
}
在C中使用堆栈
string str = "ABCDEFG";
Stack<char> stack=new Stack<char>();
foreach (var c in str)
{
stack.Push(c);
}
char[] chars=new char[stack.Count];
for (int i = 0; i < chars.Length; i++)
{
chars[i]=stack.Pop();
}
var result=new string(chars); //GFEDCBA
在C中使用堆栈
string str = "ABCDEFG";
Stack<char> stack=new Stack<char>();
foreach (var c in str)
{
stack.Push(c);
}
char[] chars=new char[stack.Count];
for (int i = 0; i < chars.Length; i++)
{
chars[i]=stack.Pop();
}
var result=new string(chars); //GFEDCBA
如果你避免拆分/替换/反转/合并。。。这会有点难看!Reverse是IEnumerable的扩展方法,而不是string方法。。。这会有点难看!Reverse是IEnumerable的扩展方法,而不是string方法。这就是我要求的上述算法的精巧版本。感谢kovilpatti C Sharperher,这是另一个最好的解决方案->这是我所要求的上述算法的完美版本。谢谢科维尔帕蒂C夏珀这里是另一个最好的解决方案->@StanR。我相信你是对的。不过这个概念很有趣。@StanR。我相信你是对的。不过这个概念很有趣。倒装句子的好例子。谢谢你举个例子把句子倒转过来。谢谢:-条件是我不应该使用像linq这样的框架特性。谢谢你的回答。它干净又漂亮。:-条件是我不应该使用像linq这样的框架特性。谢谢你的回答。它干净漂亮。这是Java而不是C!不管怎样,逻辑。。。现在找出区别并确保使用System.Text。这是Java而不是C!不管怎样,逻辑。。。现在找出差异,确保使用System.Text.Hi,我知道这是一个老问题,但我一直在寻找上述问题的就地算法。你的解决方案与我的非常相似。我想知道你是否有任何证明文件可以证实你的说法,即这确实是存在的?它肯定与我对就地的理解一致,但我关心的是我们对临时变量的使用,公平地说,这也在使用内存…嗨,我知道这是一个老问题,但我一直在寻找上述问题的就地算法。 你的解决方案与我的非常相似。我想知道你是否有任何证明文件可以证实你的说法,即这确实是存在的?它肯定与我对就地的理解一致,但我担心我们使用临时变量,公平地说,这也在使用内存。。。