algorithm - 颠倒单词的顺序——时间复杂度?

标签 algorithm data-structures string

输入:“我的名字是 Pritam” 输出:“Pritam 是我的名字”

到目前为止我已经写了这个,但是我对时间复杂度有点困惑

public string ReverseWordsInAString(string str)
    {
        char[] temp = str.ToCharArray();
        int startIndex = 0;
        int endIndex = str.Length - 1;
        temp = ReverseString(temp, startIndex, endIndex);
        endIndex = 0;
        foreach (char c in temp)
        {
            if(c == ' ')
            {
                temp = ReverseString(temp, startIndex, endIndex-1);
                startIndex = endIndex + 1;
            }
            if (endIndex == str.Length-1)
            {
                temp = ReverseString(temp, startIndex, endIndex);
            }
            endIndex++;
        }
        str = new string(temp);
        return str;
    }

    public char[] ReverseString(char[] chr, int start, int end)
    {
        while (start < end)
        {
            char temp = chr[start];
            chr[start] = chr[end];
            chr[end] = temp;
            start++;
            end--;
        }
        return chr;
    }

当我从 for 循环调用 ReverseString 方法时,我认为它不再是 O(n) 解决方案。如果我错了,请纠正我。有没有人有更好的解决方案。

最佳答案

在Java中

String str= "My Name is Pritam";
String arr[] = str.split(" ");
for(int i = arr.length-1 ; i >=0 ; i--){
   System.out.println(arr[i]);
}

关于algorithm - 颠倒单词的顺序——时间复杂度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5895185/

相关文章:

git - Recursive Three-Way Merge算法有哪些突出问题?

c - 我的二维数组边界算法有什么问题?

arrays - 根据匿名哈希数组中的另一个值直接访问值

algorithm - 新近度是次要优先级的优先级队列?

algorithm - Hadoop 适合哪种类型的并行算法?

java - (LeetCode) 包含 Duplicate III

c++ - 巨大的图形存储问题

java - 编译时常量在 Switch Case Java 中的使用

python - Python 中的字符串关键字搜索

javascript - 调试 Javascript 中的正则表达式