【发布时间】:2017-03-27 09:01:49
【问题描述】:
我必须为面试解决一个问题,但我什么都不明白。 问题是,对于像“我们喜欢远足”这样的字符串,要像这样反转字符串:“ew ekil gnikih”,这意味着要像这样爆炸字符串:str.split(" ") 然后,每个单词要反转和添加到新字符串中。
问题出现在问题的最后,因为是在询问有关复杂性的问题,例如: “ - 预期的最坏情况时间复杂度为 O(N)” - 预期的最坏情况空间复杂度为 O(N)(不计算输入参数所需的存储空间)
我这样解决了这个问题:
public static String solution(String S){
if(S.length()>1 && S.length()<200000){
String toReturn = "";
String[] splitted = null;
if(S.contains(" ")){
splitted = S.split(" ");
}
else{
splitted = new String[]{S};
}
for(int i=0;i<=splitted.length-1;i++){
String wordToChange = splitted[i];
String reversedWord = "";
for(int j=wordToChange.length()-1;j>=0;j--)
reversedWord+=wordToChange.charAt(j);
toReturn+=" " + reversedWord;
}
return toReturn.trim();
}
return null;
}
我应该如何处理复杂性请求? 谢谢!
【问题讨论】:
-
你不明白什么?您是在问如何计算代码的时间复杂度/空间复杂度?
-
是的,第一个问题是我的解决方案是否可行,以及如何计算复杂性,我必须对此请求做什么?
标签: java time-complexity space-complexity