I deal with quite complex recursion issues in Java.
"Given the string, recursively (no loops) calculate the number of lowercase characters" x "in the string"
countX("xxhixx") → 4 countX("xhixhix") → 3 countX("hi") → 0
-
public int countX(String str) { if (str == null || str.length() == 0) return 0; else if (str.length() == 1) return str.charAt(0) == 'x' ? 1 :0; else { return (str.charAt(str.length()-1) == 'x' ? 1 : 0 ) + countX(str.substring(0,str.length()-1)); } }
It works great. But I would like to know if there is a better way to write this. I find this code complex for a simple problem.
, , , , . . , , , . ( , String.substring, , , ).
String.substring
, , , , , :
public int countX(String str) { if(str == null || str.isEmpty()) return 0; return (str.charAt(0) == 'x' ? 1 : 0) + countX(str.substring(1));
null , 1 .
null
, substring . str.length().
substring
str.length()
1 - else:
else
public int countX(String str) { if (str == null || str.length() == 0) return 0; } return (str.charAt(str.length()-1) == 'x' ? 1 : 0 ) + countX(str.substring(0,str.length()-1)); }
?
public static int countX(String str) { if (str.length() == 0) { return 0; } int count = 0; if (str.charAt(0) == 'x') { count++; } return count + countX(str.substring(1)); }
:
public int countX(String str) { if (str == null) return 0; else { int occurrence = str.lastIndexOf("x"); int count = occurrence > -1 ? 1 + countX(str.substring(0, occurrence)) : 0; return count; } }
else if (str.length() == 1) , return (str.charAt(...
else if (str.length() == 1)
return (str.charAt(...
, , . , , ( , ...), , .
Source: https://habr.com/ru/post/1671391/More articles:Wistia Video продолжает загружаться в iPhone 6 - iosJQuery call element located inside append () with id - jquerySwift: использование оператора switch в touchsBegan - iosPHP Regex that only matches valid, valid URLs - urlSetuptools extension extension for using CMake in setup.py? - c ++Is it possible to automatically derive class_weight from flow_from_directory in Keras? - kerasGenerating random numbers that are twice as likely to expose even numbers - javaОпределение матрично-векторного оператора деления Юлии - matrixSymfony Testing - ClockMock / DateTime - phphttps://translate.googleusercontent.com/translate_c?depth=1&pto=aue&rurl=translate.google.com&sl=ru&sp=nmt4&tl=en&u=https://fooobar.com/questions/1671396/add-stylus-to-a-webpack-2-app-which-has-css-modules&usg=ALkJrhhqiqJdJTVWFxv-LFQId2JT-LZMMQAll Articles